JNI Easy Tutorial, Windows and Linux

Source: Internet
Author: User

About the various principles, JNI and JNA comparison of what please Baidu, here only introduce the basic use method, convenient for beginners, but also leave a note to themselves.

Introduction to the use of JNI, 4 examples of Java string and byte[] and C + + type conversion, 5 briefly describes the native method defined as static related issues

Let's just say that the JNI process is like a circle, starting with Java, declaring the native method you need, generating a corresponding. h file, building the DLL/SO Dynamic library based on this h file, and finally returning to the Java call.

The first thing to note is to separate the windows,linux,x32,x64. I did not go to the cross-platform to do this JNI, in what platform with the unified platform for the development of it, Linux Eclipse-java project on Linux to do C + + project generation. So dynamic library, on the windows on VS on the C + + project build. dll Dynamic library.

1:

Needless to say, whether it is Windows or Linux, open your eclipse to build a Java project, I am accustomed to such a directory structure

Libtest.java:

1  PackageJni_lib;2 3  Public classLibtest {4     Static {5System.loadlibrary ("Jni_lib_libtest");6     }7 8      Public native Static voidHelloWorld (String i_instr);9}

Jnitest.java:

1  Packagetest;2 3 ImportJni_lib. Libtest;4 5  Public classJnitest {6      Public Static voidMain (string[] args) {7Libtest.helloworld (NewString ("I ' m Nycko"));8     }9}

Here the Java code can be said to be all finished, when the main method executes, will call Libtest's HelloWorld method, the implementation of this method is from Jni_lib_libtest.dll (libjni_lib_libtest.so), So the project is now missing the dynamic library, the following to build this dynamic library.

2:

Whether it's Windows or Linux, you need to make sure that the command line can run Javac, do not install the JDK yourself and set environment variables. The following Windows demo, Linux javac and Javah command usage consistent, list directory windows with the dir,linux with LS

In the. java file directory that defines native, compile the file with Javac to obtain the. class file.

Then go to the Bin directory of the project and use Javah to process the. class file that you just generated, where Javah is followed by the package name + class name in Java instead of the path.

A. h file is generated, and the file is officially recommended not to be modified oh ~, we build a corresponding dynamic library based on this. h file.

Jni_lib_libtest.h:

1 /*Do not EDIT this file-it are machine generated*/2#include <jni.h>3 /*Header for Class Jni_lib_libtest*/4 5 #ifndef _included_jni_lib_libtest6 #define_included_jni_lib_libtest7 #ifdef __cplusplus8 extern "C" {9 #endifTen /* One * Class:jni_lib_libtest A * Method:helloworld - * Signature: (ljava/lang/string;) V -  */ theJniexportvoidJnicall Java_jni_1lib_libtest_helloworld -(JNIENV *, Jclass, jstring); -  - #ifdef __cplusplus + } - #endif + #endif

3:

(Windows) to create a new project in Visual Studio, select the Visual C + + Win32 Console application, click Next and then the application type re-election to the DLL, complete.

(Linux) Linux under a new project is not a new directory so simple, Haha, a new jni_lib_libtest.cpp, not necessarily the name.

Copy the. h file from step 2 into the project, and then write the C + + file

Jni_lib_libtest.cpp: The function name is copied from the. h file, and then you need to add your variable name after the parameter type. Types such as jstring from Java can not be directly used as a C + + string, most of the variables require JNI method to do the conversion, here first introduces the operation of JNI, more detailed code implementation first ignored.

//jni_lib_libtest.cpp: Defines an export function for a DLL application. //#include"stdafx.h"
Linux don't add this file
#include"jni_lib_libtest.h"#include<iostream>using namespacestd;/** class:jni_lib_libtest* method:helloworld* Signature: (ljava/lang/string;) V*/Jniexportvoidjnicall Java_jni_1lib_libtest_helloworld (jnienv*env, Jclass, jstring j_i_instr) { Char*I_instr; I_instr= const_cast<Char*> (Env->getstringutfchars (J_I_INSTR,false)); if(I_instr = =NULL) {cout<<"I_instr = = null!"<<Endl; return;/*OutOfMemoryError already thrown*/} cout<<"OutPut in jni_lib_libtest.cpp!"<<Endl; cout<<"helloworld! I_instr is:"<< I_instr <<Endl; Env-Releasestringutfchars (J_i_instr, i_instr);}

(Windows) then you can click (Build-Build solution), generate the corresponding. dll dynamic library, compile does not pass the words to see what the error is, there may be a problem is the project Sdk,include path and so on the property setting problem, I used the sdk= 10.0.14393.0, additional include directory =%java_home%\include;%java_home%\include\win32;% ( additionalincludedirectories). Specific problem specific analysis, self-solve oh ~. It is also important to note that the 32 and 64-bit problems, 64-bit Java project of course corresponds to 64-bit dynamic library, my machine is 64, Java project is built by default is 64 so here vs generated dynamic library select x64 to compile.

(Linux) a command, simple

Then put this DLL (. So) dynamic library into the Java project directory and customize your directory structure. I have built a Jnilib folder to put DLL (. So) files in the root directory.

If you run Java now, or error, really plug, the original also need to modify the configuration, add the following path.

Expand JRE System Library, double-click Native Library location, select the directory where you store the dynamic library

Then you can run your Java program, not yet to check the Windows System.loadlibrary only need to write the file name before, suffix. dll does not need to write, Linux is more lib and. So do not, only the middle of the dynamic library name can be.

The output is as follows:

4: Introduction of two commonly used type conversions

String gets:

Gets the passed-in parameter string:jstring java_string, where const_cast<char*> is to remove the const attribute
    Char* str_cpp;      = const_cast<charfalse));      if (Str_cpp = = NULL)        {return/*/     }  // do something    env->releasestringutfchars (java_string, str_cpp);

Srting return:

     Char* str;      // Do something     return Env->newstringutf (str);  

Byte[] Get:

Get Jbytearray Java_byte
     int byte_len= env->getarraylength (java_byte);     BYTE* byte_value= (byte*) (Env->getbytearrayelements (Java_byte,0));

Byte[] Return:

     int Ten ;     BYTE* byte_value=new byte[] ();      = env->Newbytearray (byte_len);     Env0, Byte_len, (jbyte*) byte_value);      return JARRRV;

5: Questions about whether the native method in Java is defined as static:

First: The method defined as static does not need to create an instance of the class to be called, the second parameter of the generated. h file is the Jclass type, because it is not an instance, so Estimated (insufficient Java Foundation)If you want to use this parameter on C + +, you can only call other member variables or methods that are static. Then: the non-static method requires that an instance of the class be created before it can be called by the instance, and the. h file is the second argument of the Jobject type, which is the instance object that invokes the method, which can be used in C + + to get the other members of the Java object. So If you modify the relevant definitions in Java Engineering, remember to modify the. c/.cpp file according to the newly generated. h file, which must be on top!

JNI Easy Tutorial, Windows and Linux

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.