Microsoft KB Archive/222092

= How To Call Native (DLL) Code From Java Using JNI =

Article ID: 222092

Article Last Modified on 5/10/2007

-

APPLIES TO


 * Microsoft Java Virtual Machine
 * Microsoft Visual J++ 6.0 Standard Edition
 * Microsoft Software Development Kit for Java 3.1

-



This article was previously published under Q222092



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 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. 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 "[SDK-Java]\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 </li>  Write the C/C++ code based on the generated header file:
 * 1) include "TestJNI.h"
 * 2) include <stdio.h>

JNIEXPORT void JNICALL Java_TestJNI_greetings(JNIEnv *env,jobject jobj) { printf("Hello from Visual C++!"); }                   </li>  Compile the C/C++ code: cl greet.cpp -Ic:\sdk-java.31\include -Fegreet.dll -MD -LD </li>  Test the application: jview TestJNI </li></ul>

<div class="moreinformation_section">

MORE INFORMATION
Things to note:
 * In the call to System.loadLibrary, omit the ".dll" extension from the native library's filename.
 * To support legacy native code, just have your DLL's function redirect the call to the legacy code.

(c) Microsoft Corporation 1999, All Rights Reserved. Contributions by Joseph B. Hall, Microsoft Corporation.

<div class="references_section">