[英]java jna - get byte array by reference java.lang.IndexOutOfBoundsException
I'm using JNA and I get a strange error getting a byte array. 我正在使用JNA,我得到一个字节数组的奇怪错误。
I use this code: 我用这个代码:
PointerByReference mac=new PointerByReference();
NativeInterface.getMac(mac);
mac.getPointer().getByteArray(0,8)
And it throws a IndexOutOfBoundsException: Bounds exceeds available space : size=4, offset=8 also if I'm sure thate the byte returned is a 8byte length. 并抛出一个IndexOutOfBoundsException:Bounds超出可用空间:size = 4,offset = 8如果我确定返回的字节长度为8byte。 I tried to get that array as String: 我试图将该数组作为String:
mac.getPointer().getString(0)
And here I get successfully a String 8 chars lenght. 在这里,我成功地获得了一个String 8 chars lenght。 Can you understand why? 你明白为什么吗?
Thank you. 谢谢。
PointerByReference.getValue()
returns the Pointer
you're looking for. PointerByReference.getValue()
返回您正在寻找的Pointer
。 PointerByReference.getPointer()
returns its address. PointerByReference.getPointer()
返回其地址。
mac.getPointer().getByteArray(0, 8)
is attempting to read 8 bytes from the PointerByReference
allocated memory (which is a pointer), and put those bytes into a Java primitive array. mac.getPointer().getByteArray(0, 8)
试图从PointerByReference
分配的内存(它是一个指针)中读取8个字节,并将这些字节放入Java原始数组中。 You're asking for 8 bytes but there are only 4 allocated, thus the corresponding error. 你要求8个字节但是只分配了4个,因此产生了相应的错误。
mac.getPointer().getString(0)
is attempting to read a C string from the memory allocated for a pointer value (as if it were const char *
, and convert that C string into a Java String
. It only bounds-checks the start of the string on the Java side, so it will keep reading memory (even if it is technically out of bounds) until it finds a zero value. mac.getPointer().getString(0)
试图从为指针值分配的内存中读取一个C字符串(好像它是const char *
,并将该C字符串转换为Java String
。它只限制 - 检查在Java端启动字符串,因此它将继续读取内存(即使它在技术上超出范围),直到找到零值。
EDIT 编辑
mac.getValue().getByteArray(0, 8)
will give you what you were originally trying to obtain (an array of 8 bytes). mac.getValue().getByteArray(0, 8)
将为您提供最初尝试获取的内容(8字节数组)。
EDIT 编辑
If your called function is supposed to be writing to a buffer (and not writing the address of a buffer), then you should change its signature to accept byte[]
instead, eg 如果您的被调用函数应该写入缓冲区(而不是写入缓冲区的地址),那么您应该将其签名更改为接受byte[]
,例如
byte[] buffer = new byte[8];
getMac(buffer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.