Search code examples
javac++cjna

How should I pass and return unsigned int by value from Java to C/C++ in jna


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)


Solution

  • 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);
        }
    }