title: Returning null from native methods using JNI
body: <p>I have some native code which returns a jbyteArray (so byte[] on the Java side) and I want to return null. However, I run into problems if I simply return 0 in place of the jbyteArray.</p>
  
  <p>Some more information:
  The main logic is in Java, the native method is used to encode some data into a byte stream. don;t ask.. it has to be done like this. Recently, the native code had to be changed a bit and now it runs horribly horrible slow. After some experimentation, which included commenting out all code in the native method before the return, it turns out that returning 0 causes the slowdown. When returning an actual jbyteArray, everything is fine.</p>
  
  <p>Method signatures for my code:</p>
  
  <p>On the C++ side:</p>
  
  <pre><code>extern "C" JNIEXPORT jbyteArray JNICALL Java_com_xxx_recode (JNIEnv* env, jclass java_this, jbyteArray origBytes, jobject message)
  </code></pre>
  
  <p>On the Java side:</p>
  
  <pre><code>private static native byte[] recode(byte[] origBytes, Message message);
  </code></pre>
  
  <p>The native code looks something like this:</p>
  
  <pre><code>jbyteArray javaArray;
  if (error != ERROR) {
      // convert to jbyteArray
      javaArray = env-&gt;NewByteArray((jsize) message.size);
      env-&gt;SetByteArrayRegion(java_array, 0, message.size, reinterpret_cast&lt;jbyte*&gt;(message.buffer()));
      if (env-&gt;ExceptionOccurred()) {
          env-&gt;ExceptionDescribe();
          error = ERROR;
      }
  }
  if (error == ERROR) {
      return 0; // Does NOT work - doesn't crash, just slows everything down horrible.
  }
  else {
      return javaArray; // Works perfectly.
  }
  </code></pre>
  
  <p>Does anyone know of any reasons that this could happen? Is it valid to return NULL from a native method in place of a jbyteArray, or is there another procedure to return null back to Java. Unfortunately, I had no luck on Google.</p>
  
  <p>Thanks!</p>
  
  <p>EDIT: Added additional information.</p>