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

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

+6
source share
1 answer

What I do is create a regular DirectByteBuffer and change its 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 now on, you can access ByteBuffer by referencing the base address. I did this to access memory on network adapters for a null copy and worked fine.

You can create a DirectByteBuffer for your address directly, but this is more obscure.


An alternative is to use Unsafe (this only works in the OpenJDK / HotSpot JVM and in native byte order)

 Unsafe.getByte(address); Unsafe.getShort(address); Unsafe.getInt(address); Unsafe.getLong(address); 
+15
source

Source: https://habr.com/ru/post/944640/


All Articles