Java JNI principle detailed introduction and simple example code

Java JNI principle

JNI is an important function in the Java standard platform. It makes up for the lack of Java's platform independent advantage. While Java realizes cross platform, it can also interact with the dynamic libraries of other languages (such as C and C + +), giving other languages the opportunity to give full play to their advantages.

With the support of Java standard platform, JNI mode is easier to implement and use. The following knowledge map is summarized here:

example:

Environmental description: Ubuntu 10.4 2 lts system

Listing 1: Src / COM / magc / JNI / HelloWorld java

Enter the SRC directory and compile the Java class,

Command: javac/ com/magc/jni/HelloWorld. java

In this HelloWorld Generate HelloWorld. Java in the directory where it is located class

Then use javah to generate header files,

Command: javah - JNI com magc. jni. HelloWorld

Generate com in current directory_ magc_ jni_ HelloWorld. H header file, which is used by C and C + + programs to reference and implement the functions therein

Program listing 2: com_ magc_ jni_ HelloWorld. h

Note: 1) this header file does not need to be compiled by the user and is directly referenced by other C and C + + programs. 2) Java in this header file_ com_ magc_ jni_ HelloWorld_ The displayhello (jnienv *, jobject) method is the interface that will interact with the dynamic link library in the future, and the name needs to be consistent.

Program listing 3: Src / JNI_ helloworldImpl. cpp

This C + + file implements the functions in the above header file. Note that the method function names should be consistent. Compile and generate the dynamic library libhello so,

Command: G + + - shared - I / usr / lib / JVM / java-6-openjdk / include JNI_ helloworldImpl. cpp -o libHello. so

After success, the dynamic link library libhello. Will be generated in the current directory So file.

With the specific dynamic library, you can run java to call the native method of JNI program class,

Command: Java - DJava library. path=. com. magc. jni. HelloWorld

The input result is from JNI_ helloworldImpl. cpp :Hello world !

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>