Pregunta

I have following C++ structs and functions:

typedef struct _Phase_Information
{
  char infoMessage[MAX];
} INFORMATION;

typedef struct _Informations
{
  int infoCount;
  INFORMATION *infoArray;
} INFORMATIONS ;

int GetInformations(INFORMATIONS *pInfos);

I use them like this:

INFORMATIONS informations;
INFORMATION * informationArray = new INFORMATION[MAX_INFOS];
informations.info = informationArray;
int error = GetInformations(&informations);

Now I want to use my C++ library in Java by using JNA ... so I did the following:

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 {};
}

I tried to call the library like this:

Informations.ByReference informations = new Informations.ByReference();
informations.infoArray= new Information.ByReference();
int error = CLib.GetInformations(Informations);

Information[] test =(Information[])informations.infoArray.toArray(Informations.infoCount);

Some times I only retrieve the first element of the array but the rest of the time my Java crashes ... so I believe it is related to not allocating memory on the java site but I cannot get any further :/

¿Fue útil?

Solución

Native char corresponds to Java byte.

Note that your example is passing an array of size one to GetInformations.

Aside from that incorrect mapping, which may very well be the cause of your crash, your mapping looks OK.

EDIT

You should initialize the infoCount to the size of the array you're passing in ("1" in your example). If you want to pass in a larger array, you'll need to call .toArray() on informations.infoArray prior to calling GetInformations(). Memory for additional array elements is allocated when you call Structure.toArray(); until then you only have memory allocated for a single element.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top