Using Microsoft® J/Direct to call Win32 DLLs from Java code is straightforward. A short Java application that displays a message box using the @dll.import compiler directive demonstrates this.
class ShowMsgBox { public static void main(String args[]) { MessageBox(0, "It worked!", "This message box from Java", 0); } /** @dll.import("USER32") */ private static native int MessageBox(int hwndOwner, String text, String title, int MyStyle); }
This class has a function declaration (MessageBox) and a function definition (main). The main function is the standard entry point for Java applications (not applets). It calls the Windows API MessageBox directly and easily.
The declaration of MessageBox is just a standard Java native method declaration, preceded by a special comment called a directive that tells the compiler what DLL it'll find the MessageBox entry point in. The @dll.import directive tells the compiler that the MessageBox method will link to the Win32 USER32.DLL using the J/Direct protocol rather than the RNI protocol.
Note @dll.import and the other compiler directives are Microsoft extensions to the compiler and are disabled by default. When compiling source code that contains compiler directives, use the /x- option.
For example, to compile ShowMsgBox.java, type the following compiler command:
jvc /x- ShowMsgBox
In addition, the Microsoft VM provides automatic type marshaling from String objects to the null-terminated strings expected by C.
Note Any method in any class can call ShowMsgBox.MessageBox, as does the code in main( ) previously mentioned.
Because code that uses J/Direct can do anything, it's considered untrusted. Therefore, applications can run it, but not applets. It is possible, however, to wrap code that calls J/Direct in a Java wrapper object that you sign as safe in one or more categories.
It is not necessary to indicate whether the ANSI MessageBox (MessageBoxA) function or the Unicode MessageBox function (MessageBoxW) should be called. In the previous example, the ANSI version is always called. Calling Different Versions of DLL Functions explains how to use the auto modifier to call the optimal version of the function, depending on the version of Microsoft® Windows® that is hosting the application.
Using RNI is more powerful and generates faster code, but it is considerably more complex. This power and complexity are demonstrated by the RNI Message Box example.