0

我有以下 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 站点上分配内存有关,但我无法进一步了解:/

4

1 回答 1

2

本机char对应于 Java byte

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

除了不正确的映射(这很可能是您崩溃的原因)之外,您的映射看起来还不错。

编辑

您应该将 初始化为infoCount您传入的数组的大小(在您的示例中为“1”)。如果你想传入一个更大的数组,你需要在.toArray()调用informations.infoArray 之前调用GetInformations()Structure.toArray()调用;时为额外的数组元素分配内存 在那之前,您只能为单个元素分配内存。

于 2013-10-18T20:12:02.767 回答