First, write a Java file that contains the native method
public class Myjni {public native void display (); Public native double sum (double x, double y); public static void Main (string[] args) { }}
Next, compile this Java file into an. h file
Javah Myjni
After executing this command, a MyJni.h file is produced in the directory
Third, write a. c file that introduces just the header file
#include <jni.h> #include "MyJni.h" #include <stdio.h>jniexport void Jnicall java_myjni_display (jnienv *env , Jobject obj) { printf ("Hello JNI"); return;} Jniexport jdouble jnicall java_myjni_sum (jnienv *env,jobject obj,jdouble a,jdouble b) { return a+b;}
D. Compile the. c file into. O, and then convert to. so or. dll files
Gcc-fpic-d_reentrant-i JDK Path/jdk1.8/include-i jdk path/jdk1.8/include/linux-c myjni.c
The above command compiles the C file into an. o file.
gcc-shared Test.o-o libtest.so
The above command compiles the. o file into a. so file.
Test it in the Java method just now.
public class Myjni { static { system.load ("absolute path/libtest.so"); } Use of JNI keyword Native// this keyword determines that our methods can be used in C files //Only declare, do not have to implement public native void display (); Public native double sum (double x, double y); public static void Main (string[] args) { Myjni myjni = new Myjni (); System.out.print (Myjni.sum (1, 1)); System.out.print ("\ n"); Myjni.display (); }}
Linux platform Java call so library-jni use example