Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a byte array from Java to C++ with JNI without copy [duplicate]

I wanted to pass a large byte[] from Java to C++. I know that I could use Java ByteBuffers to share memory between C++ and Java as follows:

    ByteBuffer bb;
    bb = ByteBuffer.allocateDirect(3);
    byte[] byteArray = new byte[] { 0x01, 0x02, 0x03 };
    bb.put(byteArray);
    modifyByteBuffer(bb); //native function

and access it in C++ through:

uint8_t *iBuf = (uint8_t*) env->GetDirectBufferAddress(buf1);

However, the bb.put(byteArray) operation, is a copy. If I use ByteBuffer.wrap(byteArray), then I can't access the byte array in the C++ side with env->GetDirectBufferAddress. How can I solve this dilemma and pass on a byte[] without needing to do a copy.

like image 840
Hossein Avatar asked Jan 28 '26 14:01

Hossein


1 Answers

You need to call:

GetPrimitiveArrayCritical

and

ReleasePrimitiveArrayCritical

for references to the byte[]. Don't bother with the ByteBuffer at all.

like image 152
bmargulies Avatar answered Jan 31 '26 03:01

bmargulies