A basic understanding of Java: The JNI principle (reprinted + modified) JNI is an important feature of the java standard platform. It makes up for the major advantages of Java's independence from the platform, while implementing cross-platform Java, Java can also interact with dynamic libraries in other languages (such as C and C ++), giving other languages the opportunity to take advantage of this. With the support of the java standard platform, the JNI mode is easier to implement and use. The following knowledge is summarized here: Environment Description: Ubuntu 11.04
Step 1:
Program 1 src/COM/magc/JNI/helloworld. Java
Class helloworld {private native void print (); public static void main (string [] ARGs) {New helloworld (). print ();} static {system. loadlibrary ("hello"); // libhello. so }}
Compile helloworld. Java
Run the following command in the command line:
javac HelloWorld.java
Step 2:
Generate helloworld. h
Run the following command in the command line:
javah -jni HelloWorld
Helloworld. H is generated in the current folder. Open helloworld. h and you will find the following code:
/* Do not edit this file-it is machine generated */# include <JNI. h>/* Header for class helloworld */# ifndef _ included_helloworld # DEFINE _ included_helloworld # ifdef _ cplusplusextern "C" {# endif/** class: helloworld * method: print * Signature: () V */jniexport void jnicall java_helloworld_print // java_helloworld_print this function is used in later C files and must be consistent (jnienv *, jobject ); # ifdef _ cplusplus} # endif
Implement helloworld. c
Enter the following code to create the helloworld. c file:
#include <jni.h>#include <stdio.h>#include "HelloWorld.h"JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj){printf("Hello World!\n");}
Step 3:
Compile and generate libhelloworld. So
Run the following command in Linux to complete compilation:
cc -I/usr/lib/jvm/java-6-sun/include/linux/ -I/usr/lib/jvm/java-6-sun/include/ -fPIC -shared -o libHello.so HelloWorld.c
(The preceding command is a line and should not be copied directly. libhello. So is the name of system. loadlibrary ("hello") in Java.
Step 4
Declare database address
java -Djava.library.path='.' HelloWorld
Compiled successfully
YY @ YY :~ /Androd_jin/hellowrold/src $ Java-djava. Library. Path =. com. magc. JNI. helloworld
From jni_helloworldimpl.cpp: Hello world!