Obtaining the Error Code Set by a DLL Function

Visual Studio 6.0

Do not invoke the Win32 function GetLastError to obtain an error code set by another DLL call. Because the Microsoft VM may execute function calls of its own in the process of executing Java code, the error code may have been overwritten by the time you get to it.

To reliably access the error code set by a DLL function, you must use the setLastError modifier to instruct the VM to capture the error code immediately after invoking that method. For performance reasons, this is not done by default. You can then invoke the com.ms.dll.DllLib.getLastWin32Error method to retrieve the error code. Each Java thread maintains separate storage for this value.

For example, the FindNextFile function returns status information through the error code. FindNextFile would be declared as follows:

/** @dll.import("KERNEL32",setLastError) */
  static native boolean FindNextFile(int hFindFile,
                              WIN32_FIND_DATA wfd);

A typical call would appear as:

import com.ms.dll.DllLib;

boolean f = FindNextFile(hFindFile, wfd);
if (!f) {
  int errorcode = DllLib.getLastWin32Error();