Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a direct ByteBuffer from a pointer solely in Java?

Or do I have to have a JNI helper function that calls env->NewDirectByteBuffer(buffer, size)?

like image 559
Trevor Bernard Avatar asked May 09 '13 15:05

Trevor Bernard


1 Answers

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);
like image 160
Peter Lawrey Avatar answered Sep 28 '22 18:09

Peter Lawrey