简体   繁体   English

我应该如何通过Java将值中的unsigned int从Java传递并返回到C / C ++

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

My C++ function 我的C ++函数

extern "C" {
   DECLSPEC unsigned int STDCALL doNumberThing(unsigned int some_number);
}

My Java Interface 我的Java介面

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); 显然,在处理仅对一种或另一种不匹配类型有效的值(int与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. 其他地方的一个答案建议使用“ IntByReference”,但是除非我误解了,否则他们谈论的是long *,而不是按值传递的实际无符号int。

(This is trimmed down example code, if there's a syntax error, let me know in the comments and I'll update the question) (这是精简的示例代码,如果存在语法错误,请在注释中告知我,然后我将更新问题)

JNA provides the IntegerType class , which can be used to indicate an unsigned integer of some particular size. JNA提供了IntegerType该类可用于指示某些特定大小的无符号整数。 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. 您必须long使用Java才能以原始形式保存本机unsigned int ,因为它的值可能不在Java int的范围内,但是通常您可以传递IntegerType对象,并且仅在需要时才拉出原始值。

public class UnsignedInt extends IntegerType {
    public UnsignedInt() {
         super(4, true);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM