RobotRock
RobotRock

Reputation: 4449

JNA Java struct from pointer

I have a struct, which is not fully described like the original C one.

    public class DISPLAY_DEVICE extends Structure {
        public char DeviceName[] = new char[32];
        public int StateFlags;
    }

Whereas it actually needs, way, more variables. However it will take me a long time to port them all over. Now I create the struct and pass the pointer to a dll function, and try to use device.read(); to regain the variables. However, the variables return empty. So my question is, do I need to fill out the whole struct? Or is there something else wrong?

    DISPLAY_DEVICE displayDevice = new DISPLAY_DEVICE();
    int i = 0;
    while((CLibrary.INSTANCE.EnumDisplayDevicesA(Pointer.NULL, i, displayDevice.getPointer(), 0))) {
        System.out.println("screen" + i);
        displayDevice.read();
        System.out.println(displayDevice.StateFlags);
        System.out.println(displayDevice.DeviceName);

Upvotes: 0

Views: 1177

Answers (1)

technomage
technomage

Reputation: 10069

At a minimum, you must define the structure to be the same size as its native counterpart (you can pad it with a byte[] field for stuff you don't care about).

For example:

public class MyStruct extends Structure {
   public char[] DeviceName = new char[32];
   public char StateFlags;
   public byte[] dontcare = new char[128];
}

You can also use JNAerator to auto-generate mappings from a C header if the definition is not available in JNA's platform.jar.

Upvotes: 4

Related Questions