I need to allocate array of bytes inside JNI C-function. Then transmit this array into Java code as a byte[] object. I know there is a function NewByteArray, but it takes as input only size of byte array, so I can’t use custom memory allocation functions. In my case I need to use very specific nonstandard malloc-like allocation function from Linux. There should be no additional copying because of very limited resources.
1
votes
2 Answers
2
votes
If you use a byte[], then you must allocate it from the Java heap and allow it to control your memory management.
However, you can use a ByteBuffer, which allows you to perform your memory management in the native code. You can allocate a chunk of memory in your native code and access it from Java without a copy.
2
votes
You can't do it that way. Data sent via JNI to Java MUST come from the java memory pool. You cannot allocate it from anywhere else, because it will be treated as a java object, meaning the Java GC will move it around and delete it as needed.
You have to use NewByteArray, and then you can initialize the array from any C pointer you want, allocated any way you want. But it will have to copy those values over.