如何通过参考与JNA
问题描述:
传递结构我想调用此函数:如何通过参考与JNA
extern "C" xxx_SERVICE_API int initSocket(socketStruct* skStruct);
在C定义
++ dll.socketStruct是如下所定义的结构:
typedef struct
{
int a;
int b;
} mystruct;
在Java等效代码是:
public interface MyDllClass extends Library {
public static class MyStructure extends Structure {
public static class ByReference extends MyStructureRef
implements Structure.ByReference{
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"a","b"});
}
public int a;
public int b;
}
//Native function
int initSocket (MyStructure.ByReference sks);
MyDllClass INSTANCE = (MyDllClass)Native.loadLibrary("Mydll",
MyDllClass.class);
}
我怎样才能调用这个本机fucntion与参考结构作为参数? 谢谢
谢谢你的回答。你根据我一个构造器添加到我的结构:
public interface MyDllClass extends Library {
public static class MyStructure extends Structure {
public MyStructure() {
idModule = 0;
nbModules = 0;
nbQueueInModule = 3;
portList = new int[128];
serverList = new char[128][20];
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[]{"a","b","portList","serverList"});
}
public int a;
public int b;
public int[] portList;
public char[][] serverList;
}
//Native function
int initSocket (MyStructure.ByReference sks);
MyDllClass INSTANCE = (MyDllClass)Native.loadLibrary("Mydll",
MyDllClass.class);
}
在主我写了这个代码:
MyStructure mySocket = new MyStructure();
MyDllClass.INSTANCE.initSocket(mySocket);
此代码调用本机功能时,因为空指针异常的失败。 你有想法吗?
答
所有JNA Structure
参数默认参考(struct*
)语义。
当作为结构成员出现时,它们默认使用值语义。
提供ByReference
和ByValue
标记接口用于需要补充行为的位置。如果默认行为是你想要的,你不需要额外的输入。
您应该始终提供一个基于Pointer
的构造函数,以便您定义Structure
,它避免了由JNA分配的多余内存。