1

I'm using JNA and I get a strange error getting a byte array.

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. I tried to get that array as String:

mac.getPointer().getString(0)

And here I get successfully a String 8 chars lenght. Can you understand why?

Thank you.

1 Answer 1

3

PointerByReference.getValue() returns the Pointer you're looking for. PointerByReference.getPointer() returns its address.

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. You're asking for 8 bytes but there are only 4 allocated, thus the corresponding error.

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.

EDIT

mac.getValue().getByteArray(0, 8) will give you what you were originally trying to obtain (an array of 8 bytes).

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, e.g.

byte[] buffer = new byte[8];
getMac(buffer);
Sign up to request clarification or add additional context in comments.

5 Comments

Ok, but than how to read the bytearray values and not the pointer?
Using getValue() my jvm goes in ACCESS_VIOLATION error and crashes... :-( I can not understand why with getString(0) it works...
Take a moment and read how pointers work. If you don't understand that, you'll only be guessing.
I'm betting your native code doesn't do what you're implying it does. What is the actual declaration? Does the native code write a pointer to the supplied address, or does it write data to the supplied address?
Your last edit solved my trouble... it was so simple, but I did not try that because i thought to use some ByReference object. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.