如题,我在java中使用了jna调用dll,dll中有个结构体有一些unsigned int类型参数,在java中我尝试用int接收,在我的demo.dll中调用可以获取正确的值
代码如下:
demo.dll 的头文件
#pragma once
#define DECLSPEC extern "C" _declspec(dllexport)
typedef struct demoStruct
{
unsigned int flag;
}demoStruct;
typedef struct demoStruct2
{
demoStruct * demoStruct;
}demoStruct2;
DECLSPEC unsigned int getData();
DECLSPEC demoStruct2 * getStruct();
demo.dll的 源文件:
#include "pch.h"
#include "demo.h"
#include <stdio.h>
unsigned int getData() {
unsigned int a = 43534;
return a;
}
demoStruct2 * getStruct() {
struct demoStruct * strut;
strut = new demoStruct();
unsigned int a = 43534;
strut->flag = a;
struct demoStruct2 *strut2;
strut2 = new demoStruct2();
strut2->demoStruct = strut;
return strut2;
}
然而在实际项目中使用int获取到的值是不正确的
实际项目dll 部分源码:
/*所有获取信息的结构体*/
typedef struct SqSdpcInfo
{
char *fileName;
SqPicHead *picHead;
}SqSdpcInfo;
typedef struct SqPicHead
{
unsigned int flag;
}SqPicHead;
java中对应结构体:
public class SqSdpcInfo extends Structure {
public String fileName;
public SqPicHead.ByReference picHead;
public SqSdpcInfo() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("fileName", "picHead");
}
public SqSdpcInfo(Pointer peer) {
super(peer);
}
public static class ByReference extends SqSdpcInfo implements Structure.ByReference {
};
public static class ByValue extends SqSdpcInfo implements Structure.ByValue {
};
public class SqPicHead extends Structure {
public int flag;
public SqPicHead() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("flag");
}
public SqPicHead(Pointer peer) {
super(peer);
}
public static class ByReference extends SqPicHead implements Structure.ByReference {
};
public static class ByValue extends SqPicHead implements Structure.ByValue {
};
以下是java调用dll代码
SqSdpcInfo.ByReference sqOpenSdpc = DecodeSdpc.Instance.SqOpenSdpc(filepath);
总结:demo中使用int可以正确的获取dll中 unsigned int 对应的值,而正式项目中int获取的数值不对
C++与Java通信,要进行高低位转换。
接受的话建议用int来接受unsigned int
jni头文件里面的类型jint对应java里面的int类型,原文是
typedef int jint;
unsigned int 和 int 本身都是占8个字节,所以用int来接受dll中的unsigned int。
如果使用long的话,则直接 long rate = x.rate; 即可,不需要进行取位。
0x 0000 0000 0000 0000
^从这里到右边为rate的值,占右边八个字节
直接用jnit,代码如下:
jint rate =x.rate;
你可以参考一下,刚才我试了一下在JNI中定义一个un int ,在java中直接用int接。不会发生错误。你可以排查一下JNI中的语法或定义的问题哦
个人觉得应该和int还是unsigned int没关系,你demo和正式的项目代码并不相同,demo中直接返回结构成员unsigned int,正式项目代码中结构引用了另外的结构,我觉得可能是这里出现的问题。有帮助请采纳谢谢!
和类型没关系
请试一下 jint rate =x.rate;
我没弄过这个,我这里提一下,看看对你有没有帮助Arrays.asList("flag")
和Arrays.asList("fileName", "picHead");
,这两句代码的意思是将引号里面的单词转换成list,会不会是这里有问题,你把引号去了试试