如何从地址位置获取直接字节缓冲区 [英] how to get a direct byte buffer from an address location
本文介绍了如何从地址位置获取直接字节缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这个opencv示例中,Mat 对象有一个 nativeObj
字段,返回一个表示对象地址的 long(即 140398889556640
).因为对象内数据的大小是已知的,所以我想直接访问 Mat 对象的内容,返回一个字节缓冲区.
In this opencv example, the Mat object has a nativeObj
field, returning a long that represents the address of the object (i.e 140398889556640
). Because the size of the data within the object is known, I wish to access the contents of the Mat object directly, returning a byte buffer.
最好的方法是什么?
推荐答案
您可以使用 DirectByteBuffer 包装地址或使用 Unsafe.
You can wrap the address with a DirectByteBuffer or use Unsafe.
虽然您可以这样做,但您可能不应该这样做.我会先探索所有其他选项.
While you can do this, you probably shouldn't. I would explore all other options first.
// Warning: only do this if there is no better option
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.allocateDirect(128);
long addr = ((DirectBuffer) bb).address();
ByteBuffer bb2 = wrapAddress(addr, bb.capacity());
bb.putLong(0, 0x12345678);
System.out.println(Long.toHexString(bb2.getLong(0)));
}
static final Field address, capacity;
static {
try {
address = Buffer.class.getDeclaredField("address");
address.setAccessible(true);
capacity = Buffer.class.getDeclaredField("capacity");
capacity.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
}
public static ByteBuffer wrapAddress(long addr, int length) {
ByteBuffer bb = ByteBuffer.allocateDirect(0).order(ByteOrder.nativeOrder());
try {
address.setLong(bb, addr);
capacity.setInt(bb, length);
bb.clear();
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
return bb;
}
这篇关于如何从地址位置获取直接字节缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文