JNI for Android Development invoke local C library topic (i): Use of JNI

Source: Internet
Author: User
Tags directory create

JNI, a technique used to develop a local C function library. A bridge for linking Java and C or C + + languages. In the development of some Android projects, we need to use this technology. Then the nonsense is not much to say, get into the chase.

Development of JNI, need to use the NDK, this everyone should know. A Linux development environment is also required. In general, you can use a virtual machine to install a ubantu, Bo Master was engaged in the development of Linux, this is still relatively familiar. But for most Android developers, it's too expensive to get a virtual machine. Well, we need to build a development environment that simulates Linux. This blogger will not say, directly on the link

NDK Environment Setup

In fact, the above blog only need to finish the third step, if it is to download and install Google's official integration of Eclipse, the third step can not be done.

Well, when everything is ready, let's use an example to explain how to develop a JNI project.


First, create a new Android projectThis normal use, is to create a new Android project

Second, C language method realization.1. New local native methodIn general, we need to use the C language implementation of the method, we need to use the native keyword to decorate, these methods can be placed in any one class, Bo Master for convenience, all put into a class. Reference code:
public class Dataprovider {public native int add (int x, int y);//public native String Sayhelloinc (string s);p ublic native Int[] Intmethod (int[] iNum);}

2, compile the native method here to use C language to implement three methods, in general, we use the JNI technology, are used for encryption. Therefore, the above three methods should be a common method. For this use, we need to use this class to compile a header file that generates C code javah. First, we have to go to the cmd window in the SRC folder in the Android project (if it is JDK1.6, you need to go to the/bin/classes directory, the blogger is JDK1.7, so enter the SRC directory), and then execute Javah Com.example.ndkpassdata.DataProvider (need to use full-path full-class name here)

Then we refresh the project, we will find in the SRC directory generated a. h header file,:
3. Creating a JNI directory create a new folder named Jni in the project, the name must not be mistaken,
Copy the new header file to the folder, and then create a. c file with the same name. After starting the file, we found that the three methods we have just written have been generated:

4. c File This time, we need to write these three methods in the new. c file. c File How to write, I believe the C language students should understand, about C code in how to convert Java incoming parameters and call Java method, You can refer to the jni.h header file, which has a detailed interface call method. Here bloggers are not described, directly on all the code, with detailed comments:
#include <stdio.h> #include "com_example_ndkpassdata_dataprovider.h" #include <android/log.h> #include <string.h> #define LOG_TAG "Clog" #define LOGD (...) __android_log_print (Android_log_debug, Log_tag, __va_args__) #define Logi (...) __android_log_print (Android_log_info, Log_tag, __va_args__)//Converts a string format in the Java language to a string format in the C language. char* Jstring2cstr (jnienv* env, jstring jstr) {char* Rtn = Null;jclass clsstring = (*env)->findclass (env, "java/lang/St Ring "), jstring Strencode = (*env)->newstringutf (env," GB2312 "); Jmethodid mid = (*env)->getmethodid (env, Clsstring, "GetBytes", "(ljava/lang/string;) [B"); Jbytearray Barr = (Jbytearray) (*env)->callobjectmethod (env, JSTR , Mid,strencode); String. GetByte ("GB2312"); Jsize alen = (*env)->getarraylength (env, Barr); jbyte* ba = (*env)         Getbytearrayelements (env, Barr, Jni_false); if (Alen > 0) {rtn = (char*) malloc (alen + 1); "memcpy" (RTN, BA, Alen); Rtn[alen] = 0;} (*env)->releasebytearrayelements (env, Barr, BA, 0);  return RTN;} Jniexport jint jnicall java_com_example_ndkpassdata_dataprovider_add (jnienv * env, Jobject Jobject, Jint x, jint y) {//Want to Logcat Console Print Log logd ("x=%d", X); Logi ("y=%d", y);//LOG.I (TAG, "SSS"); return x + y;} Jniexport jstring jnicall java_com_example_ndkpassdata_dataprovider_sayhelloinc (JNIENV * env, Jobject jobject, jstring STR) {char* c = "Hello";//the string in Java cannot be directly manipulated in the C language//The string in Java is converted to a char array in the C language char* CStr = JSTRING2CSTR (env, str); Strcat (CStr , c); LOGD ("%s", CStr), return (*ENV)->newstringutf (env, CSTR);} Jniexport jintarray jnicall Java_com_example_ndkpassdata_dataprovider_intmethod (JNIENV * env, Jobject Jobject,       Jintarray Jarray) {//Jarray traversal array jint* (*getintarrayelements) (jnienv*, Jintarray, jboolean*);//length of the array jsize (*getarraylength) (jnienv*, Jarray);//each element in the array +5int length = (*env)->getarraylength (env, jarray);//Get pointer initial position int* array = (*env) Getintarrayelements (env, Jarray, 0); int i = 0;for (; i < length; i++) {* (array + i) + = 5;} return jarRay;} 

5. Writing android.mk filesThe file is written in the NDK directory under the Docs directory, open android-mk.html, which is used to say. Here bloggers have to say the general must write.
Local_path: = $ (call My-dir)//return current C code directory
Include $ (clear_vars)//Clear all configuration files that have a local start are not clear Local_path
Local_module: = Hello//The name of the library function strictly adheres to the makefile format lib. So if the preceding Lib is not automatically generated
Local_src_files: = hello.c//source file name is the name of the. c file that you just created.
Include $ (build_shared_library)//Join library functionBecause the log function of C is used in the previous code, it is necessary to include the declaration of the Library reference in the. mk file, as shown in the following code:
Local_path: = $ (call My-dir)   include $ (clear_vars)   local_module    : = Libhello   Local_src_files: = Hello.clocal_ldlibs + =-llog   include $ (build_shared_library)

6, compile C file when the Android file is written, everything is ready, this time we only need to call the NDK to compile the project can last. So dynamic library file. This time you need to start Cygwin, and then come to the project directory, call the Ndk-build command. Process:

When the compilation is completed, we refresh the project, we will find an extra obj folder, in the Libs folder will also be more than a Armeabs folder, in this case we have just compiled the generated library.
Third, C language function library method callSo after compiling, we need to call the method just now, this time is simple. Where it is called, a static block of code is required to take advantage of system.loadlibrary ("Hello") and the method to import the library file that was just produced. See the code in detail:
public class Mainactivity extends Activity {dataprovider provider;static {system.loadlibrary ("Hello");} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);p Rovider = new Dataprovider ();} public void Click1 (view view) {int result = Provider.add (6, 8); SYSTEM.OUT.PRINTLN (result);} public void Click2 (view view) {String str = provider.sayhelloinc ("freedom"); Toast.maketext (Getapplicationcontext (), str, 0). Show (); public void Click3 (view view) {int[] arr = new int[] {5, 6, 7, 8, 9};p Rovider.intmethod (arr); for (int i:arr) {SYSTEM.O Ut.println (i);}}}

Well, the process of using JNI to develop a local native method has been explained, and it is worth noting that if the Local. c file is changed, we need to call Ndk-build to recompile the. c file, which is a good time to remove the local cache directory obj folder. Hope to help the people who see this article.

JNI for Android Development invoke local C library topic (i): Use of JNI

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.