I’m using various Win32 API functions in my Java application and I use GetLastError to get information on failed API calls.
Most of the time it works, but now I found a case where something seems to reset the last error.
This is what I do both in my Java application and my VB6 application:
- I open the handle to the process with PID 4 (System)
- I call
GetModuleFileNameExwith that handle. - I call
GetProcessImageFileNamewith that handle.
Now both API functions fail as expected (they return zero) and in my VB6 application GetLastError returns 87 (“Invalid parameter”) after both API calls.
But in my Java application, only after GetModuleFileNameEx the last error is set to 87. After GetProcessImageFileName it is always zero.
What can I do about this?
EDIT:
Here are the JNA declarations:
public interface PsApi extends StdCallLibrary {
PsApi INSTANCE = (PsApi) Native.loadLibrary("psapi", PsApi.class,
W32APIOptions.UNICODE_OPTIONS);
int GetModuleFileNameEx(WinNT.HANDLE hProcess, WinDef.HMODULE hModule,
char[] lpFilename, int nSize);
int GetProcessImageFileName(WinNT.HANDLE hProcess, char[] lpImageFileName,
int nSize);
}
And the calling code for GetProcessImageFileName
char[] buffer = new char[2048];
int result = PsApi.INSTANCE.GetProcessImageFileName(hProcess, buffer,
buffer.length);
if (result == 0) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return new String(Arrays.copyOf(buffer, result));
And for GetModuleFileNameEx
char[] buffer = new char[2048];
int result = PsApi.INSTANCE.GetModuleFileNameEx(hProcess, hModule, buffer,
buffer.length);
if (result == 0) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return new String(Arrays.copyOf(buffer, result));
The documentation describes two options:
The problem with calling
GetLastErroris that the JNA framework and indeed the Java runtime may call Windows function which reset the error. So you should not attempt to callGetLastErrordirectly.