JNI detailed tutorial

Source: Internet
Author: User

After three days, I finally got a little eye off and shared it with everyone.

Android calls C ++ code

As for the ndk environment, I will not talk about it here (http://blog.csdn.net/yinzhengbo/article/details/7268207)


First, briefly describe the implementation functions, add students, modify student information, query all student information, and find students by name.


1. First, create a student object class containing fields (name, sex, age) in the project ),

Studenttojni include (addstu (student Stu), upstu (student Stu), getstu (string name), getstus)


2. CMD-> javac (compiling the studenttojni. Java file) to generate a bytecode File


3. Generate the header file (javah) Cd and execute javah-JNI package name + class name under the project classess directory (class name should not be suffixed). A. h file will be generated in classes.


4. Create and copy the JNI folder under the project root directory. to the JNI folder, find the installation directory of the ndk and find android. MK, application. the MK folder is stored in the JNI directory. Note that if you use the C ++ library. add to the MK file (app_stl: = stlport_shared)

The other usage of the two files is not described here (goolgle)


5. Create a file in the JNI folder. CPP file. It is best to have the same name as the header file. Then copy all functions in the header file to the CPP folder and import the header file (# include <name. h>), of course, JNI should also be imported. h header file, in fact, we mainly do is to use JNI to convert the type passed in Java to the type required by C ++, then, convert the value returned by C ++ to the type required by Java through JNI. JNI. the H header file provides many conversion methods and value methods. You can open the ndk installation directory (platforms \ Android-9 \ arch-Arm \ USR \ include) view JNI. h header file


6. Specific implementation (File: Android. mk, application. mk, jnitest. H, jnitest. cpp ):

Mainly implement the jnitest. cpp File

(1) Reference necessary header files (JNI. H, jnitest. H, vector) and introduce the namespace (using namespace STD ;)


(2) define a structure. The content in the structure is the same as the field in student in the Java class (struct student {char * Name; int age, int sex };) (a semicolon must exist), define a vector, used to save the entered student information (because it is a user input, the length is not fixed, so the vector is used to save) (vector <student>
Stus)


(3) define the jstringtosstring method to convert the jstring type to the char pointer type code goolgle. JNI converts the object type passed in by Java to the corresponding type of JNI. For example
String = JNI jstring, Java student = JNI jobject ......)


(4) add student information: addstu (jnienv * ENV, jobject OBJ, jobject valobj)


// Obtain jclass object jclass CLS = env-> getobjectclass (valobj); // The getfieldid method uses the name field in jclass. The parameter list (jclass object, field name, and field type) is similar to the Java reflection // getobjectfield method, which obtains the value of the specified field from the passed jobject object valobj. Parameter List (jobject object, jfieldid object) Pay attention to type conversion; jstring name = (jstring) ENV-> getobjectfield (valobj, env-> getfieldid (CLS, "name ", "ljava/lang/string;"); jint age = (jint) ENV-> getobjectfield (valobj, env-> getfieldid (CLS, "Age ", "I"); jint sex = (jint) ENV-> getobjectfield (valobj, env-> getfieldid (CLS, "sex", "I ")); // create a structure type object jstringtostring to convert the jstring type to char * student Stu = {jstringtostring (ENV, name), (INT) age, (INT) Sex }; // Add an object stus to the end of the vector. push_back (Stu );

(5) Modify student information: upstu (jnienv
* ENV, jobject OBJ, jobject valobj)

         jclass cls=env->GetObjectClass(objValue);jstring name=(jstring)env->GetObjectField(objValue,env->GetFieldID(cls,"name","Ljava/lang/String;"));jint sex=(jint)env->GetObjectField(objValue,env->GetFieldID(cls,"sex","I"));jint age=(jint)env->GetObjectField(objValue,env->GetFieldID(cls,"age","I"));char * searchName=jstringTostring(env,name);for(int i=0;i<stus.size();i++){student stu=stus.at(i);if(strcmp(stu.name,searchName)==0){stus.at(i).sex=(int)sex;stus.at(i).age=(int)age;}}


(6) query student information: getstu (jnienv
* ENV, jobject OBJ, jstring Str)

 const char *nameStr=env->GetStringUTFChars(str,0);jclass objectClass=(env)->FindClass("com/myjni/activity/Student");jfieldID name=env->GetFieldID(objectClass,"name","Ljava/lang/String;");jfieldID sex=env->GetFieldID(objectClass,"sex","I");jfieldID age=env->GetFieldID(objectClass,"age","I");for(int i=0;i<stus.size();i++){student stu=stus.at(i);if(strcmp(stu.name,nameStr)==0){env->SetObjectField(obj,name,env->NewStringUTF(stus.at(i).name));env->SetIntField(obj,sex,stus.at(i).sex);env->SetIntField(obj,age,stus.at(i).age);}} return obj;


(7) obtain all student information: getstus (jnienv * ENV, jobject OBJ)


class objClass = (env)->FindClass("java/lang/Object");jobjectArray args=0;jsize len=stus.size();args=env->NewObjectArray(len,objClass,0);jclass objectClass=(env)->FindClass("com/myjni/activity/Student");jfieldID name = (env)->GetFieldID(objectClass,"name","Ljava/lang/String;");jfieldID age = (env)->GetFieldID(objectClass,"age","I");jfieldID sex = (env)->GetFieldID(objectClass,"sex","I");for(int i=0;i<len;i++){jobject tempObj=env->AllocObject(env->GetObjectClass(obj));student stu=stus.at(i);env->SetObjectField(tempObj,name,env->NewStringUTF(stus.at(i).name));env->SetIntField(tempObj,age,stu.age);env->SetIntField(tempObj,sex,stu.sex);env->SetObjectArrayElement(args,i,tempObj);}return args;

7. Java code call


 static{System.loadLibrary("stlport_shared");System.loadLibrary("HW");}StudentToJNI jni=new StudentToJNI();jni.add(new Student());jni.update(new Student());jni.getStu("tom");jni.getStus();

Source code download

Only a part of the errorxice is completed due to time issues.

Snake

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.