Java JNA u32t 返回指针(内存)的值



我尝试使用 JNA 访问 C++ DLL 的方法。

定义如下:

u32t OpenPort(u8t valueA, char* valueB, u32t* handle);

我不确定如何映射 u32t 以及如何使用指针或内存获取返回值?

我做了这样:

int OpenPort(byte valueA, String valueB, IntByReference handle); //u32t OpenPort(u8t type, char* myString, u32t* handle);

和呼叫

IntByReference handle = new IntByReference();            
byte i = 0;
int error = myClass.OpenPort(i, "my string", handle);
System.out.println(error  + " - " + handle.getValue());

结果为"0 - 0"。

错误"0"很好,但返回值不应为 0。由于这是一个值,我需要传递给其他方法,例如:

int ClosePort(IntByReference handle); //u32t ClosePort(u32t handle);

如果我然后开始:

error = myClass.ClosePort(handle);

返回错误指出端口句柄无效。

来自 DLL 创建器的示例 c# 代码如下所示:

UInt32 handle;
UInt32 error;
error= OpenPort(0, "teststring", out handle);
xError = ClosePort(handle);

欢迎来到 StackOverflow。

Pointer实际上指向具有 32 位值的本机内存。但是,仅映射到Pointer并不能告诉您指向位置的位置是什么。

应使用IntByReference类对指向 32 位值的*uint32_t或类似指针进行建模。 该方法将返回一个指针,但您可以使用getValue()方法来检索所需的实际值。

我还注意到您已经将NativeLong用于返回类型,但它明确指定为 32 位,因此您想使用int. 仅当long定义为 32 位或 64 位(具体取决于操作系统位数(的情况下,才使用NativeLong

请注意,Java 没有有符号整数与无符号整数的概念。 虽然该值将是 32 位int但您需要通过将负值转换为无符号对应项来处理自己的代码中的负值。

所以你的映射应该是:

int MethodName(byte valueA, String valueB, IntByReference returnValue);

然后致电:

IntByReference returnValue = new IntByReference();
MethodName(valueA, ValueB, returnValue);
int theU32tValue = returnValue.getValue();

最新更新