I have a C++ Function in my DLL that needs an uint8_t array as an input Parameter, so the array looks something like that:
uint8_t input[input_length] = { 0x30, 0x41, 0x80, 0x8A...};
I want to use this function in Java with JNA, which means I have to creat an uint8_t array in Java. My first approach was to create an byte array like:
byte[] input = { 0x30, 0x41, 0x80, 0x8A...};
But then I realized that an uint8_t Variable in C++ has a range from 0..255, but a byte Variable in Java has an range from -128..127, and as you can see this array contains Values that are over 127 (like 0x8A), which means my Java declaration here is not valid. So my question is what type in Java is equivalent to uint8_t?
public class UInt8. Represents an 8-bit unsigned integer.
sizeof(uint8_t *) is 8size of pointer. The size of the pointer depends on the target platform and it's usually 8 bytes on x64, 4 bytes on 32 bit machines, 2 bytes on some 16 bit microcontroller, etc.
Java doesn't have unsigned types. But it's not a big problem, since signed overflow in Java is defined as two's complement, you can just pass the byte
to where JNA expects uint8_t
. It's only a bit inconvenient to work with:
byte[] input = { 0x30, 0x41, (byte)0x80, (byte)0x8A...};
To read uint8_t
back you'd do (x & 0xFF)
to strip the sign extension and work with the result as an int
.
The value stored in a byte is a determinate one regardless how you interpret it, signed or unsigned that matters.
You can verify this easily with this code:
byte test = (byte)255;
System.out.println(test & 0xFF);
which outputs 255
.
This means that once you created your byte[]
with the values you need (and casting each value to byte allows you to set unsigned values). Then you are fine, on your JNI side you'll use:
jbyte* data = GetByteArrayElements(...)
and you'll be able to use it as an unsigned array of bytes by directly casting it if needed (uint8_t*)data
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With