Q222092 HOWTO: Call Native (DLL) Code From Java Using JNI
The information in this article applies to:
- Microsoft® virtual machine (Microsoft VM)
- Microsoft® Visual J++®, version 6.0
- Microsoft® Visual Studio® 6.0
- Microsoft® SDK for Java, version 3.1
SUMMARY
This article details the process of calling native C/C++ code (in a DLL) from Java using JNI (Java Native Interface). This article presumes a working knowledge of the Microsoft® Visual C++® command-line compiler, CL.EXE.
- Make sure that you are using a version of Microsoft's SDK for Java that supports JNI. JNI support was added in December of 1998 to SDK version 3.1 and above. For more information, visit the Java lawsuit information center.
- Make sure that the environment variable, CLASSPATH, contains a reference to %Windir%\Java\Classes\Classes.zip and C:\ (assuming that C:\ is your development drive).
- Make sure that your %SDKDIR%\Bin directory is included in your path (for JavaH, JVC, and JView).
- Make sure that Visual C++ is properly set up for command-line use. See your Visual C++ documentation for details.
- Write your Java code:
public class TestJNI {
public native void greetings();
static {
System.loadLibrary("greet");
}
public static void main(String args[]) {
new TestJNI().greetings();
}
}
- Compile the Java file:
jvc TestJNI.java
- Run JavaH on the generated class file:
javah -jni TestJNI
- Write the C/C++ code based on the generated header file:
#include "TestJNI.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_TestJNI_greetings(JNIEnv *env,jobject jobj) {
printf("Hello from Visual C++!");
}
- Compile the C/C++ code:
cl greet.cpp -Ic:\sdk-java.31\include -Fegreet.dll -MD -LD
- Test the application:
jview TestJNI
MORE INFORMATION
Things to note:
- In the call to System.loadLibrary, omit the ".dll" extension from the native library's file name.
- To support legacy native code, just have your DLL's function redirect the call to the legacy code.
REFERENCES
For more information on the legal action brought by Sun regarding Microsoft's Java agreement, visit the Java lawsuit information center.
For the latest Knowledge Base articles and other support information on Visual J++ and the SDK for Java, please see the following pages on the Microsoft Technical Support site:
http://support.microsoft.com/support/visualj/ 
http://support.microsoft.com/support/java/ 
© 1999 Microsoft Corporation. All rights reserved. Terms of use.