[英]Struct with array of structs JNA
我有以下C ++结构和函数:
typedef struct _Phase_Information
{
char infoMessage[MAX];
} INFORMATION;
typedef struct _Informations
{
int infoCount;
INFORMATION *infoArray;
} INFORMATIONS ;
int GetInformations(INFORMATIONS *pInfos);
我这样使用它们:
INFORMATIONS informations;
INFORMATION * informationArray = new INFORMATION[MAX_INFOS];
informations.info = informationArray;
int error = GetInformations(&informations);
现在我想通过使用JNA在Java中使用我的C ++库...所以我做了以下事情:
public class Information extends Structure {
public char[] infoMessage = new char[MAX];
public Information () { super(); }
protected List<? > getFieldOrder() {
return Arrays.asList("infoMessage ");
}
public Information (char infoMessage []) {
super();
if ((infoMessage .length != this.infoMessage .length))
throw new IllegalArgumentException("Wrong array size !");
this.infoMessage = infoMessage ;
}
public static class ByReference extends Information implements Structure.ByReference {};
public static class ByValue extends Information implements Structure.ByValue {};
}
public class Informations extends Structure {
public int infoCount;
public Information.ByReference infoArray;
public Informations () { super(); }
protected List<? > getFieldOrder() {
return Arrays.asList("infoCount", "infoArray");
}
public Informations(int infoCount, Information.ByReference infoArray) {
super();
this.infoCount= infoCount;
this.infoArray= infoArray;
}
public static class ByReference extends Informations implements Structure.ByReference {};
public static class ByValue extends Informations implements Structure.ByValue {};
}
我试着像这样调用库:
Informations.ByReference informations = new Informations.ByReference();
informations.infoArray= new Information.ByReference();
int error = CLib.GetInformations(Informations);
Information[] test =(Information[])informations.infoArray.toArray(Informations.infoCount);
有时我只检索数组的第一个元素,但剩下的时间我的Java崩溃了......所以我认为它与不在java站点上分配内存有关但我无法进一步:/
Native char
对应于Java byte
。
请注意,您的示例是将大小为1的数组传递给GetInformations
。
除了可能导致崩溃的错误映射之外,您的映射看起来还不错。
编辑
您应该将infoCount
初始化为您传入的数组的大小(在您的示例中为“1”)。 如果你想在更大的阵列来传递,你需要调用.toArray()
上informations.infoArray
调用之前 GetInformations()
调用Structure.toArray()
时,将分配用于其他数组元素的内存; 在此之前,您只为单个元素分配了内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.