Java class: UserInfo
Public class UserInfo {static {System. loadLibrary ("userinfo");} // directly access the public String mUserName; public int mUserAge; public long mMoney; public UserInfo () {} public int getUserAge () field from JNI () {return mUserAge;} public native void setUserName (String name); public native void setUserAge (int age); public native void setUserMoney (long money );}
Three of the setting methods are expected to be implemented using C. Several Functions in JNI are involved here:
1. FindClass: locate a class and return the jclass object.
2. GetObjectClass: gets the type of an object and returns the jclass object.
3. GetFieldID: obtains the field ID.
4. SetIntField/SetLongField/SetObjectField: Set the field value.
Based on the above methods, you can write the code as follows:
/* * Class: com_iflytek_testjni_UserInfo * Method: setUserName * Signature: (Ljava/lang/String;)V */JNIEXPORT void JNICALL Java_com_iflytek_testjni_UserInfo_setUserName(JNIEnv *env, jobject obj, jstring jstr) {jfieldID fid;jclass cls = (*env)->GetObjectClass(env, obj);fid = (*env)->GetFieldID(env, cls, "mUserName", "Ljava/lang/String;");(*env)->SetObjectField(env, obj, fid, jstr);}/* * Class: com_iflytek_testjni_UserInfo * Method: setUserAge * Signature: (I)V */JNIEXPORT void JNICALL Java_com_iflytek_testjni_UserInfo_setUserAge(JNIEnv *env, jobject obj, jint age) {jclass objClass = (*env)->FindClass(env, "com/iflytek/testjni/UserInfo");jfieldID ageID = (*env)->GetFieldID(env, objClass, "mUserAge", "I");(*env)->SetIntField(env, obj, ageID, (int)age);}/* * Class: com_iflytek_testjni_UserInfo * Method: setUserMoney * Signature: (J)V */JNIEXPORT void JNICALL Java_com_iflytek_testjni_UserInfo_setUserMoney(JNIEnv *env, jobject obj, jlong money) {jclass objClass = (*env)->FindClass(env, "com/iflytek/testjni/UserInfo");jfieldID id = (*env)->GetFieldID(env, objClass, "mMoney", "J");(*env)->SetLongField(env, obj, id, (long)money);}
Compile Android. mk and pass the test.
Note: Because the method signature and field names are all written in the C language, the Code cannot be confused.