The Java Native Interface defines a standard naming and calling convention so the Java virtual machine can locate and invoke native methods. In fact, JNI is built into the Java virtual machine so the Java virtual machine can invoke local system calls to perform input and output, graphics, networking, and threading operations on the host operating system.
Please follow the following steps to get a basic knowledage about JNI. (my os is Linux)
step 1: Create a java file named Hello.java
class HelloJni
{
public static native void sayHello();
}
step2: Compile the HelloJni.java using javacjavac HelloJni.java
check the contain of this folder, you will find that a HelloJni.class is generated.
step3: Generate a head file using javah
javah HelloJni
Check the folder again, you'll find that a HelloJni.h is generated:
Now, open the HelloJni.h with vi editor, you can find it's contain is:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloJni */
#ifndef _Included_HelloJni
#define _Included_HelloJni
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloJni
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloJni_sayHello
(JNIEnv *, jclass);
step4: create a source file named HelloJni.c whose contain is:#include <stdio.h>
#include "HelloJni.h"
JNIEXPORT void JNICALL Java_HelloJni_sayHello
(JNIEnv *env, jclass cl)
{
printf("Hello Jni^_^\n");
}
step5: compile HelloJni.c into a *.so file using gccgcc -fPIC -I /usr/lib/jvm/java-6-sun/include -I /usr/lib/jvm/java-6-sun/include/linux -shared -o libHelloJni.so HelloJni.c
and then, check the folder again you will find a so file is generated:
step6: create a HelloJniTest.java to test it:
public class HelloJniTest
{
public static void main(String[] args)
{
HelloJni.sayHello();
}
static
{
System.loadLibrary("HelloJni");
}
}
step7: run HelloJniTest using the following command:
java -Djava.library.path=. HelloJniTest
you'll see the output: