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

后端 未结 1 1128
南旧
南旧 2020-12-29 15:10

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

相关标签:
1条回答
  • 2020-12-29 15:19

    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);
    
    0 讨论(0)
提交回复
热议问题