Use of JNI in Linux

Source: Internet
Author: User

Use of JNI in Linux

I learned how to use JNI in Android. I have never seen this cross-language call,

Java has been learned recently, not to mention JNI,

The use of JNI is very important and key for Android. So how exactly does Java call C/C ++,

I learned from the summary of the online talents and summarized the learning process by myself.

What isJNI

JNI is short for Java Native Interface and can be translated as a Java Native Interface.

Java can call the C/C ++ library through JNI.ProgramIt is undoubtedly a gospel.

JNI is an interface for Java to interact with C/C ++.

Using JNI is also costly. As we all know, Java programs run on JVM and can be platform independent.

However, if the Java program calls the nativeCode(For example, C/C ++), Java programs lose platform independence.

At least the native code must be re-compiled. Therefore, the JNI application must be well balanced. Therefore, do not select JNI,

You can choose an alternative solution, such as TCP/IP for inter-process communication. This is why the underlying layer of Google's Android platform is implemented using JNI,

However, he does not recommend that developers use JNI to develop Android applications. The platform independence of the Android app is lost.

Code instance

The following describes how to use JNI in Linux using helloworld.

Step 1:

Create a testjni. Java File

ImportJava. util .*;Public ClassTestjni {//Declare native function: the parameter is of the string type.Public Native VoidPrint (string content );//Load local library codeStatic{System. loadlibrary ("Testjni");}}

 

 

Compile the testjni. Java file: javac testjni. Java

Generate the testjni. Class file in the current folder.

Note the declaration of the print method. The keyword native indicates that the method is implemented by a native code.

In addition, pay attention to the system. loadlibrary call of the static code segment. This Code indicates that the libtestjni. So library is automatically loaded when the program is loaded.

 

Step 2:

Generate testjni. h file

Run javah-JNI testjni.

Generate testjni. h file

 /* Do not edit this file-it is machine generated  */  # Include <JNI. h> /*  Header for class testjni  */  # Ifndef _ included_testjni  # Define _ Included_testjni # Ifdef _ cplusplus  Extern   "  C  "  {  # Endif /*  * Class: testjni * method: print * Signature: (ljava/lang/string;) V  */  Jniexport  Void  Jnicall java_testjni_print (jnienv * , Jobject, jstring); # ifdef _ cplusplus}  # Endif  # Endif 

 

This file contains a declaration of the java_testjni_print function. It is very important to automatically include two parameters. Jnienv * And jobject

 

Step 3:

Create the testjni. c file

# Include <JNI. h> # Include <Stdio. h> # Include <Testjni. h> Jniexport  Void  Jnicall java_testjni_print (jnienv * ENV, jobject OBJ, jstring content ){  //  Gets the pointer to the string UTF Encoding from the instring  //  Note that the C language must be (* env)-> C ++ env->        Const Jbyte * STR = (  Const Jbyte *) (* env)-> Getstringutfchars (ENV, content, jni_false); printf (  "  Hello ----> % s \ n  "  , STR );
// Notifies the VM that the Local Code no longer needs to access the Java string through Str. ( * Env)-> releasestringutfchars (ENV, content ,( Const Char * ) Str ); Return ;}

 

// SeeJnienvSo that we can use the Java method.

// Jobject points to a handle of the Java object localfunction instantiated in this Java code, which is equivalent to the this pointer

The parameter type jstring corresponds to the string in Java, which is different here. The types in each Java are matched here.

 

Command Line input:

CC-I/usr/lib/JVM/Java-6-sun/include/Linux/

-I/usr/lib/JVM/Java-6-sun/include/

-I/home/XMP/androidproject/APK/JNI

-FPIC-shared-O libtestjni. So testjni. c

Generate: libtestjni. So Library File

 

Generate libtestjni. So in the current directory. Note that the include directory of Java must be included (set according to your system environment ),

Because libtestjni. C contains JNI. h.In libtestjni. Java, the loadlibrary method loads "testjni ",

The generated library is libtestjni.This is what Linux links stipulate,

A library must be lib + Library name +. So. You only need to provide the database name for the link.

 

-I/home/XMP/androidproject/APK/JNI is a directory of my own exercises and must be included. Otherwise, the header file testjni. h cannot be found in the. c file.

Now liblibtestjni. So is a usable library. Its function is to have a print function that corresponds to the testjni. Java file just created,

The liblibtestjni. So library is loaded in the testjni. Java class, and the print function is declared. Therefore, the print function is available in testjni. java;

So now we can use testjni. Java to call functions in library C libtestjni. So.

 

Of course, the liblibtestjni. So library can be loaded for any Java class to use its functions.

 

Step 4:

Create a helloword. Java Function

ImportJava. util .*;Public ClassHelloworld {Public Static VoidMain (string argv []) {NewHelloworld ();}PublicHelloworld (){NewTestjni (). Print ("Hello, world! ");//Call the native function print of testjni}}

 

Enter the command to compile: javac helloworld. Java

Generate helloworld. Class

 

Step 5:

Run the helloworld Program

Command Line input: Java helloworld

Output result: Hello ----> Hello, world!

Verify OK!

 

If a problem occurs in this step, if you receive an exception in Java. Lang. unsatisfiedlinkerror, you can specify the path of the shared library as follows:

Java-djava. Library. Path = '.' helloworld

 

Or enter the following command:

Export LD_LIBRARY_PATH ="HelloworldPath": $ LD_LIBRARY_PATHSetEnvironment Variable

Then Java helloworld is the same as OK

 

For a simple example, see the following reference document.

 

Reference:

Http://my.unix-center.net /~ Simon_fu /? P = 359

Http://www.ibm.com/developerworks/cn/java/l-linux-jni/

Jnienv function reference:

Http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.