My C++ function
extern "C" {
DECLSPEC unsigned int STDCALL doNumberThing(unsigned int some_number);
}
My Java Interface
package com.myplace.nativeapi;
import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
interface NativeAPI extends Library {
int doNumberThing(int some_number);
}
Obviously this has a problem when dealing with values that are only valid for one or the other of the mismatched types (int vs unsigned int); what is the recommended way to get around this? One answer elsewhere recommends "IntByReference", but unless I've misunderstood, they're talking about the long*, not the actual unsigned int being passed by value.
(This is trimmed down example code, if there's a syntax error, let me know in the comments and I'll update the question)
In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32-1. Use the Integer class to use int data type as an unsigned integer.
An unsigned integer can hold a larger positive value, and no negative value like (0 to 255) . Unlike C++ there is no unsigned integer in Java.
int64. A 64-bit signed integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). string.
You can convert an int to an unsigned int . The conversion is valid and well-defined. Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
JNA provides the IntegerType
class, which can be used to indicate an unsigned integer of some particular size. You'll have to use a Java long
to hold a native unsigned int
in primitive form, since its values may be outside the range of Java int
, but in general you can pass around the IntegerType
object and only pull the primitive value out as needed.
public class UnsignedInt extends IntegerType {
public UnsignedInt() {
super(4, true);
}
}
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