Casting to a Reference to an @dll.struct Class

One way to read and write data through a raw pointer is to cast the raw pointer to a reference to an @dll.struct class. Once this is done, you can read and write the data using normal field access syntax. For instance, suppose you have a raw pointer that you wish to access as a RECT. You can use the system method DllLib.ptrToStruct as follows:

/** @dll.struct() */
  class RECT {
    int left;
    int top;
    int right;
    int bottom;
  }

  import com.ms.dll.*;

  int  rawptr = ...;
  RECT rect = (RECT)DllLib.ptrToStruct(RECT.class, rawptr);
  rect.left = 0;
  rect.top = 0;
  rect.right = 10;
  rect.bottom = 10;

The ptrToStruct method wraps the raw pointer in a RECT instance. Unlike instances created by the new operator, this RECT instance will not attempt to free the raw pointer upon reclamation by the garbage collector because the RECT object has no way of knowing how the pointer was allocated. In addition, because the native memory was already constructed at the time ptrToStruct was called, the RECT class constructor is not called.