Search code examples
javajava-native-interfacejnienv

How to release the jbyteArray?


My native method has a method with a byte[] return value, So I use "NewByteArray" to alloc the byte[],then use return to return the jbyteArray. Should I release the jbyteArray? And how to release the jbyteArray? Thank you. I am a Java beginner and my English is poor.


Solution

  • You don't want to release the byte-array within your native method, because the caller of the native method wants to use the array in Java.

    Given that you don't hold a global reference to the created array:

    The garbage collector can then take care to remove the array object at the right time, because the local reference that the native methods holds to the array will be removed once the method returns.

    Here is an example of how such a native method could look like: How to return an array from JNI to Java?