Creating a JNI example for testing
The Java language can be extended using C and C++ to write extensions that are called using the Java Native Interface (JNI).
The JNI extensions is created by creating a Java class definition that defines the class methods as native and loads a native DLL to do that.
class HelloWorld { public native void displayMessage(); static { System.loadLibrary("HelloWorldImp"); // load HelloWorldImp.dll to implement the native interfaces } }
A full description of this process can be found on Matthew Mead’s JNI page.
Example JNI code for test
We’ve created an example based on this which also allocates some memory, deallocates some memory and causes a memory leak. You can
download the example code. To build the example follow these steps:
- Open a command prompt and change the current directory to the testJavaJNI directory in the example.
- Edit buildJava.bat, createJNIHeaders.bat, runJava.bat to point to your JAVA SDK directory.
- Run buildJava.bat
- Run createJNIHeaders.bat
- Build the HelloWorldImp.dll. The Visual Studio 6 Project (*.dsp) and Visual Studio Solution (*.sln) files are in the HelloWorld directory.
After the DLL has been built the DLL and its PDB file will be copied to the same location as the Java class files so that the DLL can be found by the Java Virtual Machine when it attempts to load the native implementation of HelloWorld.
To run the example, run runJava.bat. The example prints “Hello World!” twice. The first time does not leak memory, the second time does leak memory.