【发布时间】:2016-08-04 10:19:11
【问题描述】:
我对 JNA 编程很陌生。我有一个本机代码如下
int Data(int Number, aaa *Data, int* error);
typedef struct {
uint8 Storage;
LStr path;
int32 chart;
int32 strt;
LStr val;
int32 timedata;
} aaa;
typedef struct {
int32 cnt; /*num of bytes that follow*/
uChar str[1];
} LStrval, *LStrPtr, **LStr;
如何使用 JNA 从 Java 调用此本机函数。我尝试了几个选项,但我没有得到结果。我尝试过的选项之一如下。
接口函数
public int SetStorage_Data(int num,Storage_Data.ByReference data, Pointer error);
public class Storage_Data extends Structure{
public static class ByReference extends Storage_Data implements Structure.ByReference {}
public byte storage;
public Stringtype.ByReference savepath;
public int chart;
public int strt;
public Stringtype.ByReference val;
public int timedata;
@Override
protected List getFieldOrder() {
return Arrays.asList("storage", "savepath","chart",
"strt","val","timedata");
}
}
public class Stringtype extends Structure{
public static class ByReference extends Stringtype implements Structure.ByReference {
public ByReference(int buffersize) {
super(buffersize);
// TODO Auto-generated constructor stub
}}
public int count;
public byte[] str;
public Stringtype(int buffersize) {
str = new byte[buffersize];
count = str.length;
allocateMemory();
}
@Override
protected List getFieldOrder() {
return Arrays.asList("count", "str");
}
}
还有 Java 调用
InjectionAnalyzerInterfaces.Storage_Data.ByReference storagedata = new InjectionAnalyzerInterfaces.Storage_Data.ByReference();
int len= string.length;
InjectionAnalyzerInterfaces.Stringtype.ByReference savepath = new InjectionAnalyzerInterfaces.Stringtype.ByReference(len);
byte[] stringbyte = string.getBytes();
System.arraycopy(stringbyte, 0, savepath.str, 0, bytes);
storagedata.savepath = savepath;
storagedata.chart = 1;
storagedata.strt =1;
String temp= "all";
byte[] strtbyte = temp.getBytes();
int dd = strtbyte.length;
InjectionAnalyzerInterfaces.Stringtype.ByReference stra = new InjectionAnalyzerInterfaces.Stringtype.ByReference(dd);
System.arraycopy(strtbyte, 0, stra.str,0, dd);
storagedata.strt = stra;
storagedata.tdata = 0;
Pointer error = new Memory(5);
int status1 = lib.Set_Config_Storage_Data(deviceNumber, storagedata, error);
请帮帮我。提前谢谢你
【问题讨论】:
-
我建议您首先对这些字段使用
Pointer,然后使用各种Pointer访问方法以您想要的方式提取和格式化数据。一旦您了解了取消引用的级别,您就可以找出最明智的映射方式。但是,您有一个基本问题,因为您的字段是struct**,JNA 不会识别它,所以对Structure.read/write的所有调用完全取决于您执行。 -
@technomage 是使用
Pointer.getPointer(0)还是PointerByReference.getValue()更好? -
只有在将指针的地址作为参数传递给某物时,才应使用
PointerByReference。如果您刚刚将void**作为某个字段,请使用Pointer。
标签: java pointers structure jna