2

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.

iseki
  • 63
  • 1
  • 12
  • 1
    So your native function is returning back to Java? If so: no, there's nothing special you need to do in your native code (unless you've created a global reference to the array using `NewGlobalRef`). – Michael Jan 28 '17 at 12:36

1 Answers1

4

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?

Community
  • 1
  • 1
Calculator
  • 2,769
  • 1
  • 13
  • 18
  • You means the GC can release the jbyteArray auto? So I neednot to do anything? Thank you. – iseki Jan 28 '17 at 12:43
  • @cpdyj as Michael has pointed out: "unless you've created a global reference to the array using NewGlobalRef" – Calculator Jan 28 '17 at 12:45
  • Does that means the memory allocated to a C non-global pointer will be automatically released in Java code. Because there's no further reference to that pointer. – Summer Sun Apr 22 '19 at 09:38