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

六眼飞鱼酱① 提交于 2019-12-03 19:09:18

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/16465477/is-there-a-way-to-create-a-direct-bytebuffer-from-a-pointer-solely-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!