Step 1: Create a Java File that declares the native method (HelloWorld.java)
class HelloWorld
{
private native void print();
public static void main(String[] args)
{
new HelloWorld().print();
}
static
{
System.loadLibrary("HelloWorld");
}
}
Step 2: Compile the class using default java compiler javac, resulting a class file named HelloWorld.class
javac HelloWorld.java
Step 3: Use javah -jni to generate a C header file (HelloWorld.h). This header file will contain the prototype declaration for the native method to be implemented in C++.
javah -jni HelloWorld
Step 4: Write the C implementation (HelloWorld.c) of the native method.
#include
#include
#include "HelloWorld.h"
JNIEXPORT void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
printf("Hello World!\n");
return;
}
Step 5: Compile the C implementation into a native library, creating HelloWorld.dll
or libHelloWorld.so. Use the C compiler and linker available on the host
environment.
In Microsoft Visual Studio it can be easily done if we start a MFC dll project and then just include the header and implementation files.
Step 7: Put the dll into the Java project path and run the program.
Reference: java.sun.com/docs/books/jni/download/jni.pdf
2 comments:
Well, Shwakkhar bhai, you missed one point. You need to add jni header files in your include directory from %JDK_HOME%\include and %JDK_HOME%\include\win32.
It must be configured in the project properties otherwise it does not build the solution. (I am using Microsoft Visual Studio 2003).
Mahmudul Hasan
Oops! vul hoye gese! ...
Post a Comment