Search code examples
javac++jna

How Can I load DEVMODE using jna Structure class without garbling


I'm trying to load DEVMODE by Java.

As following the link below, I create a class SampleClass which extends com.sun.jna.Structure. Inside the SampleClass Constructor, I call #useMemory(Pointer m) and then call #read(). After I call its Constructor, each field have values. It looks fine but, value of char[] looks garbling. So I want to know the proper way to load DEVMODE.

https://msdn.microsoft.com/en-us/library/windows/desktop/dd183565(v=vs.85).aspx

the garbling field is below.

public char[] dmDeviceName = new char[32];

Solution

  • The proper way to initialize a Structure from an existing Pointer is to use the Pointer-based constructor, e.g.

    public class MyClass extends Structure {
        public char[] buffer = new char[32];
        public MyClass(Pointer p) {
            super(p);
            read();
        }
    }
    

    This avoids a superfluous memory allocation which occurs with the default constructor.

    Note that DEVMODE has a union field, whose type you should probably set before calling Structure.read(). In this case it probably won't hurt if you don't, since the fields are all primitives, but you'll likely have to manually call Structure.read() on the union field.

    You can use the system property -Djna.dump_memory=true to see the contents of native memory vis a vis your Java fields when you call toString() on the Structure. This can help you determine if you're missing a field or padding, or have an incorrectly-sized field type.