The Java language does not directly support the concept of a structure. Although Java classes containing fields can be used to emulate the concept of a structure within the Java language, ordinary Java objects cannot be used to simulate structures in native DLL calls. This is because the Java language does not guarantee the layout of the fields and because the garbage collector is free to move the object around in memory.
Therefore, to pass and receive structures from DLL methods, you need to use the @dll.struct compiler directive. When applied to a Java class definition, this directive causes all instances of the class to be allocated in a memory block that will not move during garbage collection. In addition, the layout of the fields in memory can be controlled using the pack modifier (see Structure Packing). For example, the Win32 SYSTEMTIME structure has the following definition in the C programming language:
typedef struct {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;
The correct declaration of this structure in Java is as follows:
/** @dll.struct() */
class SYSTEMTIME {
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}
The following example uses the SYSTEMTIME structure in a DLL method call:
class ShowStruct {
/** @dll.import("KERNEL32") */
static native void GetSystemTime(SYSTEMTIME pst);
public static void main(String args[])
{
SYSTEMTIME systemtime = new SYSTEMTIME();
GetSystemTime(systemtime);
System.out.println("Year is " + systemtime.wYear);
System.out.println("Month is " + systemtime.wMonth);
// etc.
}
}
Note Classes declared with @dll.struct are considered unsafe and therefore cannot be used by untrusted applets.
For more information, see: