Trevor Bernard
Trevor Bernard

Reputation: 992

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)?

Upvotes: 8

Views: 3691

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

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);

Upvotes: 21

Related Questions