Calling the Optimal Version of a DLL Function

Unfortunately, neither calling the ANSI version or the Unicode version of a DLL function is an ideal way to invoke the Win32 functions. Using the default ANSI mode allows your code to run on any Win32 platform, but causes unnecessary performance penalties on fully Unicode systems such as Microsoft Windows NT. Using the unicode modifier removes the performance penalty but restricts you to running on systems that implement the Unicode API. Fortunately, you can use the auto modifier with the @dll.import directive to call the optimal version of a DLL function based on the host operating system.

Using the auto modifier gives you the best of both worlds. The following example shows how to call the optimal version of the MessageBox function:

/** @dll.import("USER32",auto) */
  static native int MessageBox(int hwnd, String text, String title, 
                               int style);

When the auto modifier is present, the Microsoft VM determines at run time whether the underlying platform supports the Unicode APIs. If Unicode is supported, the VM acts as if the unicode modifier had been specified. Otherwise, the VM behaves as if the ansi modifier had been specified. Thus, the auto modifier allows you to generate a single binary which runs well on both ANSI and Unicode Windows systems using the optimal API set available on the given platform.

In general, the auto modifier should be used whenever you call Windows API functions. If you are calling your own DLLs, select either ansi (the default) or unicode depending on your needs.

The following list provides details of how the VM decides whether to use ANSI or Unicode when you use the auto modifier:

  1. The VM opens the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM and looks for the DWORD-named value DllImportDefaultType. This value can be one of the following:

    2 – ANSI: Uses the ANSI version always.

    3 – Unicode: Uses the UNICODE version always.

    4 – Platform: Uses ANSI or Unicode depending on the platform.

  2. If the key does not exist, or if it is set to 4 (indicating platform), the VM calls the Win32 GetVersion function and examines the high bit to determine whether the underlying platform is Microsoft Windows 95 or Microsoft Windows NT. If the platform is Windows 95, ANSI mode is used. Otherwise, Unicode mode is used.

It is not necessary to set the DllImportDefaultType registry key yourself. It exists primarily so that the installation program can set the appropriate choice on future Windows platforms. You can programmatically query the preferred mode on your platform by reading the com.ms.dll.DllLib.systemDefaultCharSize field. This field will be set to 1 on ANSI systems, 2 on Unicode systems.

The ansi, unicode, and auto modifiers can also be used with the @dll.struct directive.