具有结构数组的结构JNA

时间:2013-10-18 17:12:28

标签: java c++ arrays struct 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站点上分配内存有关但我无法进一步:/

1 个答案:

答案 0 :(得分:2)

Native char对应于Java byte

请注意,您的示例是将大小为1的数组传递给GetInformations

除了可能导致崩溃的错误映射之外,您的映射看起来还不错。

修改

您应该将infoCount初始化为您传入的数组的大小(在您的示例中为“1”)。如果您想传入更大的数组,则需要先调用.toArray() 之前的informations.infoArray 来调用GetInformations()。调用Structure.toArray()时会分配其他数组元素的内存;在此之前,您只为单个元素分配了内存。