Passing a String to a DLL Function

To pass a standard null-terminated string to a DLL function, just pass a Java String.

For example, to change the current directory, you can access the Kernel32 function CopyFile as follows:

class ShowCopyFile
{
  public static void main(String args[])
  {
    CopyFile("old.txt", "new.txt", true);
  }
  /** @dll.import("KERNEL32") */
  private native static boolean CopyFile(String existingFile, 
                                  String newFile, boolean f);
} 

Strings are read-only in Java, so the Microsoft VM will only convert the String object as an input. To allow virtual machine implementations to marshal Strings without copying the characters, String object parameters should not be passed to DLL functions that can modify the string. If the DLL function might modify the string, pass a StringBuffer object.

Strings are converted to ANSI unless the unicode or ole modifier is used, in which case the string is passed in Unicode format.

Strings cannot be declared as return types of a DLL function except in ole mode, where the native return type is assumed to be a LPWSTR allocated using the CoTaskMemAlloc function.