Or do I have to have a JNI helper function that calls env->NewDirectByteBuffer(buffer, size)?
What I do is create a normal DirectByteBuffer and change it's address.
Field address = Buffer.class.getDeclaredField("address");
address.setAccessible(true);
Field capacity = Buffer.class.getDeclaredField("capacity");
capacity.setAccessible(true);
ByteBuffer bb = ByteBuffer.allocateDirect(0).order(ByteOrder.nativeOrder());
address.setLong(bb, addressYouWantToSet);
capacity.setInt(bb, theSizeOf);
From this point you can access the ByteBuffer referencing the underlying address. I have done this for accessing memory on network adapters for zero copy and it worked fine.
You can create the a DirectByteBuffer for your address directly but this is more obscure.
An alternative is to use Unsafe (this only works on OpenJDK/HotSpot JVMs and in native byte order)
Unsafe.getByte(address);
Unsafe.getShort(address);
Unsafe.getInt(address);
Unsafe.getLong(address);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With