In-depth understanding of Android (4)-Understanding JNI in Android (bottom)

Source: Internet
Author: User

In a brief introduction to JNI in the previous article, this article briefly looks at some of the commonly used methods defined in jni.h to implement Java code calls to Android via C + +.

Reprint please indicate source: Http://blog.csdn.net/dawanganban

Introduction of one or two parameters

In the previous code we will encounter two parameters, the following to explain the two parameters

1, jnienv is the interface pointer to the available JNI function table, in C code jnienv is a pointer to the JNINATIVEINTERFACE structure, in C language jnienv must be passed in as the first parameter to each JNI function caller, such as:

(*env)->newstringutf (env, "HelloWorld");
In C + +, JNIEnv is an instance of the C + + class, and the JNI function exists as a member function, so in a JNI environment, the parameter is passed out in an unordered state, such as:

Env->netstringutf ("HelloWorld");
2. Jobject is a reference to a Java object, and if the local method is a static method, it is a class object that points to the type bytecode file.

Ii. Types of JNI data

1. Basic Type Mapping

As can be seen from the table above, the Java data type and C + + basic data type has a mapping relationship, we can use JNI when using the Natvie type directly to manipulate the native layer of data, so as not to remember the complex mapping relationship, From the name of the variable we can see that the basic data type of Java is preceded by a letter ' J ' is the corresponding C + + native type.

2. Reference type Mapping


Unlike primitive types, reference types are opaque to native methods (they cannot be used and modified directly), and JNI provides a set of APIsthat are closely related to these reference types, which are provided to native functions through jnienv interface pointers.

We can see the definition of the above type in jni.h:

Class _jobject {};class _jclass:public _jobject {};class _jthrowable:public _jobject {};class _jstring:public _jobje CT {};class _jarray:public _jobject {};class _jbooleanarray:public _jarray {};class _jbytearray:public _jarray {};CL _jchararray:public _jarray {};class _jshortarray:public _jarray {};class _jintarray:public _jarray {};class _jlo Ngarray:public _jarray {};class _jfloatarray:public _jarray {};class _jdoublearray:public _jarray {};class _jobjectA Rray:public _jarray {};typedef _jobject *jobject;typedef _jclass *jclass;typedef _jthrowable *jthrowable;typedef _jstri ng *jstring;typedef _jarray *jarray;typedef _jbooleanarray *jbooleanarray;typedef _jbytearray *jbyteArray;typedef _ Jchararray *jchararray;typedef _jshortarray *jshortarray;typedef _jintarray *jintarray;typedef _jlongArray * Jlongarray;typedef _jfloatarray *jfloatarray;typedef _jdoublearray *jdoublearray;typedef _jobjectArray *jobjectArray ;
The design of these classes, like Java, inherits from a parent class named _jobject.

Iii. examples of operation of reference types

Package Com.example.test;import Android.app.activity;import Android.os.bundle;import android.view.view;import Android.view.view.onclicklistener;import Android.widget.toast;import com.example.myfirstjniproj.r;/** * Sunshine Cockroach http:/ /blog.csdn.net/dawanganban * @author Lixiaoqiang * */public class Mainactivity extends Activity implements Onclicklistene r{@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Findviewbyid (R.id.jni_jstring_button) Setonclicklistener (this); FindViewById (R.id.jni_ Javaarray_button). Setonclicklistener (this);} @Overridepublic void OnClick (view view) {switch (View.getid ()) {Case R.id.jni_jstring_button:showtoast (jnistringtest ( "Input string")); break;case r.id.jni_javaarray_button:int[] array = jniarraytest (); Showtoast ("arr[1]=" + array[1] + ": a Rr[2]= "+ array[2]); break;default:break;}} private void Showtoast (String content) {toast.maketext (mainactivity.this, Content, Toast.length_short). Show ();} Public native string Jnistringtest (String str);p ublic native int[] jniarraytest (); Static{system.loadlibrary ("Jnitest" );}}
Header file generated by Javah

/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class Com_example_test_mainactivi Ty */#ifndef _included_com_example_test_mainactivity#define _included_com_example_test_mainactivity#ifdef __ Cplusplusextern "C" {#endif */* Class:     com_example_test_mainactivity * Method:    jnistringtest * Signature: ( ljava/lang/string;) ljava/lang/string; */jniexport jstring jnicall java_com_example_test_mainactivity_jnistringtest  (jnienv *, Jobject, jstring);/* * Class:     com_example_test_mainactivity * Method:    jniarraytest * Signature: () [I */jniexport Jintarray Jnicall Java_com_example_test_mainactivity_jniarraytest  (jnienv *, jobject); #ifdef __cplusplus} #endif #endif
C + + implementation

#include "com_example_test_mainactivity.h" #include <stdlib.h>using namespace std; Jniexport jstring jnicall java_com_example_test_mainactivity_jnistringtest  (jnienv * env, jobject obj, jstring str) {//Translate Java string into C + + string Jboolean iscopy;const char* CStr = Env->getstringutfchars (str, &iscopy);//release native string env-> Releasestringutfchars (str, CSTR);//create string jstring jstr = Env->newstringutf ("Hello World");; return JSTR;} Jniexport Jintarray jnicall java_com_example_test_mainactivity_jniarraytest  (jnienv * env, Jobject obj) {// Creates an array of 10 elements Jintarray Intarray = Env->newintarray (x), if (0! = intarray) {Jint nativearray[10];//gets the native array env-> Getintarrayregion (intarray, 0, ten, Nativearray); nativearray[1] = 10;nativearray[2] = 20;//settings Change env-> Setintarrayregion (intarray, 0, ten, Nativearray);} return intarray;}
Iv. accessing domains and getting IDs

Java has two domains: an instance domain and a static domain, each with its own copy of the instance domain, and all instances of a class share a static domain.

JNIEXPORT Jstring jnicall Java_com_example_test_mainactivity_getinstancefield (jnienv * env, Jobject obj) {//Get class Jclass clazz by object; Clazz = Env->getobjectclass (obj);//Get instance domain Idjfieldid Instancefieldid;instancefieldid = env->getfieldid (Clazz, " Instancefield "," ljava/lang/string ");//Get instance domain jobject Instancefield;instancefield = Env->getobjectfield (obj, Instancefieldid); jstring jstr = Env->newstringutf ("Get Success"); return jstr;} Jniexport jstring jnicall Java_com_example_test_mainactivity_getstaticfield (jnienv * env, Jobject obj) {jclass clazz; Clazz = Env->getobjectclass (obj); Jfieldid staticfieldid;staticfieldid = Env->getstaticfieldid (Clazz, " Staticfield "," ljava/lang/string "); Jobject Staticfield;staticfield = Env->getstaticobjectfield (Clazz, Staticfieldid); jstring jstr = Env->newstringutf ("Get Success"); return jstr;} 
In the above code we see the "ljava/lang/string" string, which is the type signature that gets the ID, and the Java Type Signature mapping table is as follows:


V. Calling methods in Java

Like the domain above, there are two types of methods in Java, instance methods and static methods, and JNI provides functions for two types of methods.

public native void Getinstancemethod ();p ublic native void Getstaticmethod ();p ublic String Instancemethod () {return ' Instancemethod ";} public static String Staticmethod () {return "Staticmethod";}
jniexport void Jnicall Java_com_example_test_mainactivity_getinstancemethod  (jnienv * env, Jobject obj) {jclass Clazz;clazz = Env->getobjectclass (obj); Jmethodid instancemethodid;instancemethodid = Env->GetMethodID (Clazz, " Instancemethod "," () ljava/lang/string "); jstring Instancemethodresult;instancemethodresult = env-> Callstringmethod (obj, instancemethodid);} jniexport void Jnicall Java_com_example_test_mainactivity_getstaticmethod  (jnienv * env, Jobject obj) {jclass clazz ; clazz = Env->getobjectclass (obj); Jmethodid staticmethodid;staticmethodid = Env->getstaticmethodid (Clazz, " Staticmethod "," () ljava/lang/string "); jstring Staticmethodresult;staticmethodresult = env-> Callstaticstringmethod (Clazz, staticmethodid);}

In-depth understanding of Android (4)-Understanding JNI in Android (bottom)

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.