Search code examples
javaarraysdata-structuresjna

C based nested array struture translation in JNA


I am quite newbie in using JNA. I am successful in translating the single structure from C-DLL into JAVA. But having problem in implementing the nested structure.

C- code is as follow:

typedef struct
{
    unsigned char x;
    unsigned char y;
    unsigned long flag;
    unsigned short length;
    unsigned short data_length;
    unsigned short status;

    struct
    {
        unsigned char val;
        unsigned short param;
    } data_1[10];


} frame_t;

My JNA based code is as follow:

pubic class frame_t extends Structure implements com.sun.jna.Structure.ByReference 
{
  public byte x;
  public byte y;
  public long flag;
  public short length;
  public short data_length;
  public short status;

public data_1 extends Structure implements com.sun.jna.Structure.ByReference 
{
    public byte val;
    public short param;
} 


}

Could anyone advice me whether I am correctly translating the nested structure ? and How I can translate the array structure of data_1 ?

Your advice in this regards will be highly appreciated.


Solution

  • I have no working installation atm, so bear with me if it does not work out of the box.

    First I would rewrite the C part as following:

    typedef struct {
        unsigned char val;
        unsigned short param;
    } data_t;
    
    typedef struct
    {
        unsigned char x;
        unsigned char y;
        unsigned long flag;
        unsigned short length;
        unsigned short data_length;
        unsigned short status;
        data_t data[10];
    } frame_t;
    

    With these changes it becomes clear what to do on java side:

    @FieldOrder({ "val", "param" })
    public class Data extends Structure {
        public byte val;
        public short param;
    }
    
    @FieldOrder({ "x", "y", "flag", "length", "data_length", "status", "data" })
    public class Frame extends Structure {
        public byte x;
        public byte y;
        public NativeLong flag;
        public short length;
        public short data_length;
        public short status;
        public Data[] data = new Data[10];
    }
    

    Of course this needs more bookkeeping code, but you didnt show any logic so I only translated the structs.

    Edit: Added FieldOrder declaration.
    Edit: Added length initialization for data and actual field names for field order.