Using the DllLib Copy Methods

Another method for reading and writing data through a raw pointer is to use the overloaded copy methods in DllLib. These methods copy data between Java arrays of various types and raw pointers. If you need to treat a raw pointer as a pointer to a string (LPTSTR), you can use one of the DllLib methods ptrToStringAnsi, ptrToStringUni, or ptrToString to parse the string and convert it into a java.lang.String object.

import com.ms.dll.*;

  int rawptr = ...;
  String s = DllLib.ptrToStringAnsi(rawptr);

! WARNING   All Java objects are subject to movement in memory or reclamation by the garbage collector. Therefore, you should not attempt to obtain a pointer to a Java array by calling a DLL function that does generic casting. The following example shows you an incorrect way to obtain the pointer:

// Do not do this!
  /** @dll.import("MYDLL") */
  private native static int Cast(int javaarray[]);

  // Inside MYDLL.DLL   
  LPVOID Cast(LPVOID ptr) 
  {
    // Do not do this!
    return ptr; // comes in as a Java array; goes out as a Java int
  } 

The value of ptr is guaranteed to be valid only for the duration of the call to the Cast function. This is because VM implementations are allowed to implement passing of arrays by copying and because garbage collection may cause the physical location of the array to be different after the call to the Cast function returns.