JNA – Java Lock the workstation

Simplify Native Code Access with JNA | Java.net

Linkage: What’s in a Name?

Our first example (LockWorkStation.java) is extremely simple, and locks the workstation when it is run (same effect as pressing the Windows logo + L keys together). It uses the User32 interface shown above to create a proxy for the Windows user32 DLL. It then calls the proxy’s LockWorkStation() method — which in turn invokes the DLL’s LockWorkStation() function. The run-time mapping of the proxy method to the DLL function is handled transparently by JNA — the user just has to ensure that the method name matches the function name exactly.

import com.sun.jna.Native; // JNA infrastructure
import libs.User32; // Proxy interface for user32.dll

public class LockWorkStation {
public static void main(String[] args) {

// Create a proxy for user32.dll …
User32 user32 = (User32) Native.loadLibrary(“user32″, User32.class);

// Invoke “LockWorkStation()" via the proxy …
user32.LockWorkStation();

}
}

To compile and run this program follow the instructions at “Running the Sample Code" below.

The absence of parameters and a return value in the LockWorkStation() call eliminates the possibility of any programming errors. But there are still two things that can go wrong with code as simple as this:

*

loadLibrary() throws a java.lang.UnsatisfiedLinkError with the message “Unable to load library … The specified module could not be found." If this error occurs check the spelling of the DLL name, and verify that the DLL is in one of the searched directories (check JNA documentation).
*

A proxy method (such as LockWorkStation()) throws a java.lang.UnsatisfiedLinkError with the message “Error looking up function … The specified procedure could not be found." If this error occurs check the spelling of the function name, and verify that the “function" is not actually a macro. The Windows API DLLs contain quite a few such macros (e.g. GetMessage(), defined in Winuser.h), so read the DLL’s documentation (and the associated header files) carefully. Macro names must be translated manually.

You shouldn’t get either of these exceptions when running LockWorkStation.java. But you can simulate these errors just by changing the name of a DLL or a function and recompiling the code. JNA does, in fact, have mechanisms to allow you to use a method name (in the proxy interface) that is different from the function name (in the DLL). More information on this feature can be found in the JNA documentation.

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

What is 11 + 9 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)