问题描述
或者我必须有一个调用env-> NewDirectByteBuffer(缓冲区,大小)的JNI辅助函数?
我所做的是创建一个普通的DirectByteBuffer并更改它的地址。
字段地址= Buffer.class.getDeclaredField(address) ;
address.setAccessible(true);
字段容量= Buffer.class.getDeclaredField(capacity);
capacity.setAccessible(true);
ByteBuffer bb = ByteBuffer.allocateDirect(0).order(ByteOrder.nativeOrder());
address.setLong(bb,addressYouWantToSet);
capacity.setInt(bb,theSizeOf);
从这一点开始,您可以访问引用基础地址的ByteBuffer。我这样做是为了访问网络适配器上的内存零拷贝而且工作正常。
你可以直接为你的地址创建一个DirectByteBuffer,但这更加模糊。 / p>
另一种方法是使用Unsafe(这仅适用于OpenJDK / HotSpot JVM和本机字节顺序)
Unsafe.getByte(address);
Unsafe.getShort(address);
Unsafe.getInt(address);
Unsafe.getLong(地址);
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);
这篇关于有没有办法只用Java在指针中创建一个直接的ByteBuffer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!