Android Jni and NDK Learning (--JNI) instance two pass-through class objects

Source: Internet
Author: User

1 Application Layer Code

Ndkparam.java is the invocation class for the JNI function, and its code is as follows:

PackageCOM.SKYWANG.NDK;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;PublicClass NdkparamExtendsActivity {PublicStaticFinal String tag= "Skywang--ndkparam";/**Called when the activity is first created.*/Private person person=Null; @OverridePublicvoidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main); LOG.D (TAG, "on Create.")); person = New Person (); for (int. i=0; i<3; i++) {Getpersoninfobyindex (person, i); LOG.D (TAG, "person[" +i+ "]--" + person ";}} method registered in// JNI private native int getpersoninfobyindex (person person, int index); static { // load local libndk_load.so library file system.loadlibrary ("Ndk_param");}}    

Person.java is the data class used to pass between Java and JNI, and its code is as follows:

Package COM.SKYWANG.NDK;  Class person {        privateintfloatpublicreturn ' mname: ' +mname+ ', MAge: ' +mage+ ', Mheight: "+Mheight;}}        

2 JNI Layer Code

NDK_PARAM.C is the file that implements and registers JNI, and its code is as follows:

#include <stdlib.h>#include <String.h>#include <stdio.h>#include <jni.h>#include <assert.h>//Gets the size of the array # define NELEM (x) (int) (sizeof (x)/sizeof ((x) [0])))//Specifies the class to register, corresponding to the full Java class name#define JNIREG_CLASS "Com/skywang/ndk/ndkparam"#define JNIPAR_CLASS "Com/skywang/ndk/person"//Introduction of log header file # include <android/log.h>//Log label#define TAG "Hello_param"//Defining Info Info#define Logi (...) __android_log_print (android_log_info,tag,__va_args__)//Defining debug information#define LOGD (...) __android_log_print (Android_log_debug, TAG, __va_args__)//Define error information#define LOGE (...) __android_log_print (android_log_error,tag,__va_args__)//Jfieldid structure for preserving the Filedid of class "Person.java"structpersonoffsets{jfieldid name; Jfieldid age; jfieldid height;} gpersonoffsets;//The structure corresponding to "Person.java", which holds the data and assigns the data to the member typedef of PERSON.JAVAstructtagperson{Char mname[10];IntMAge;FloatMheight;} person;//3 person definedstatic person gpersons[] ={ {"Skywang",25,175}, {"Eman" ,30,166}, {"Dan" ,41M172},};#define Gperson_num Nelem (gpersons)/** Get person information based on index. * Parameter Description: * ENV:JNI interface pointer. * Claszz:java class object. * Person: Input parameter, Java Object * Index: input parameter, serial number.*/Jniexport jint jnicall getpersoninfobyindex (jnienv *Env, Jobject clazz, jobject person, jint index) {//If index is invalid, returns 1 directly.if ((int) index<0 | | (int) index>=Gperson_num)Return-1;//Assigns the index member of the person Array (gpersons) to the Pperson pointer *pperson = &Gpersons[index];//Set the Java object mname jstring name = (*env)->newstringutf (env, pperson->Mname); (*env)Setobjectfield (env, person, gpersonoffsets.name, name);//Set Java Object Person's mage (*env)->setintfield (env, person, Gpersonoffsets.age, pperson->MAGE);//Set Java Object Person's mheight (*env)->setfloatfield (env, person, Gpersonoffsets.height, pperson->Mheight); LOGD ("%s index-%d mname:%s, mage:%d, mheight:%f\n", __func__, Index, Pperson->mname, Pperson->mage, pperson->Mheight);Return0;}//Initializes the function to obtain the corresponding FieldID for each member of the Java.Staticvoid Nativeclassinit (JNIENV *ENV) {Jclass Personclass = (*env)Findclass (env, jnipar_class);//Gets the mname member of the person corresponding to the FieldID, and saves it to gpersonoffsets gpersonoffsets.name = (*env)->getfieldid (env, Personclass,"Mname" ,"ljava/lang/string;");//Gets the mage member of the person corresponding to the FieldID, and saves it to gpersonoffsets gpersonoffsets.age = (*env)->getfieldid (env, Personclass,"MAge" ,"I");//Gets the mheight member of the person corresponding to the FieldID, and saves it to gpersonoffsets gpersonoffsets.height = (*env)->getfieldid (env, Personclass,"Mheight","F");}//Binding tables for Java and JNI functionsStatic Jninativemethod method_table[] ={ {"Getpersoninfobyindex","(Lcom/skywang/ndk/person;i) I", (void*) Getpersoninfobyindex},//Binding};//Registering the native method in JavaStaticint Registernativemethods (jnienv* env,Constchar*ClassName, jninativemethod* Gmethods,IntNummethods) {Jclass clazz; clazz = (*env)Findclass (env, className);if (Clazz = =NULL) {ReturnJni_false; }if (*env)->registernatives (env, Clazz, Gmethods, Nummethods) <0) {ReturnJni_false; }ReturnJni_true;}int Register_ndk_param (JNIENV *ENV) {nativeclassinit (env);//Calling the registration methodReturnregisternativemethods (env, Jnireg_class, method_table, Nelem (method_table));} // jni_onload when JNI is registered, it is executed by callback. Jniexport jint jni_onload (javavm* vm, void* reserved) {jnienv* env = NULL; jint result =-1; if (*VM)->getenv (VM, (void**) &env, jni_version_1_4)! = Jni_ok) { return result;} registe R_ndk_param (env); // return to JNI version return jni_version_1_4;}           

The code for ANDROID.MK is as follows:

Local_path: = $ (call my-dir) include $ (clear_vars) local_module    : = ndk_paramlocal_src_files: = ndk_ param.c# add support for the Log Library local_ldlibs:=-l$ (sysroot)/usr/lib-llog#  if a static. A is generated, simply add local_ldlibs:=-llog Include $ (build_shared_library) Local_path: = $ (call my-dir)      

3 Running the project

Logcat information is as follows:

d/skywang--Ndkparam:on Create. D/hello_param:getpersoninfobyindex index-0 Mname:skywang, MAge:Mheight:175.000000d/skywang--ndkparam:person[0]--Mname:skywang, MAge:mheight:175.0d/hello_param:getpersoninfobyindex index-1 Mname:eman, MAge: +, mheight : 166.000000d/skywang--ndkparam:person[1]--Mname:eman, MAge: +, mheight:166.0D/hello_param: Getpersoninfobyindex index-2 Mname:dan, MAge:Wuyi, Mheight:172.000000d/skywang--ndkparam:person[ 2]--Mname:dan, MAge:Wuyi, Mheight:172.0          

Click to download: " source code "

Android Jni and NDK Learning (--JNI) instance two pass-through class objects

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.