Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c++

c

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)

like image 450
deworde Avatar asked Nov 05 '15 12:11

deworde


People also ask

How do you treat unsigned integer in Java?

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.

Is there an unsigned int in Java?

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.

What is int64 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.

How do you make an unsigned integer?

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.)


1 Answers

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);
    }
}
like image 177
technomage Avatar answered Sep 29 '22 12:09

technomage