In-depth Android JNI object

Android JNI Getting started is implemented in C ++ Student object in the operation of Java, then look at an example of objects.

Here Insert Picture Description

Here Insert Picture Description

Here Insert Picture Description

The above code, we have no incoming Person and Student object, but get the two objects by reflection of the way.

Output log as follows:
Here Insert Picture Description
complete code testObject follows:

extern "C"
JNIEXPORT void JNICALL
Java_com_hongx_jni_MainActivity_testObject(JNIEnv *env, jobject thiz) {
    const char *person_class_str = "com/hongx/jni/Person";
    jclass person_class = env->FindClass(person_class_str);
    jobject person = env->AllocObject(person_class);
    // 初始化方法
    const char *sig = "(Lcom/hongx/jni/Student;)V";
    jmethodID setStudent = env->GetMethodID(person_class, "setStudent", sig);
    // 直接创建 Student 对象
    const char *student_class_str = "com/hongx/jni/Student";
    jclass student_class = env->FindClass(student_class_str);
    jobject student = env->AllocObject(student_class);
    // 给我们创建出来的Student对象赋值
    sig = "(Ljava/lang/String;)V";
    jmethodID setName = env->GetMethodID(student_class, "setName", sig);
    jstring value = env->NewStringUTF("刘德华");
    env->CallVoidMethod(student, setName, value);
    sig = "(I)V";
    jmethodID setAge = env->GetMethodID(student_class, "setAge", sig);
    env->CallVoidMethod(student, setAge, 89);
    // 调用Person里面的方法
    env->CallVoidMethod(person, setStudent, student);
    // 回收方式
    /*env->DeleteLocalRef(student_class); // jclass  jobject
    env->DeleteLocalRef(student);*/
}
Published 446 original articles · won praise 67 · views 240 000 +

Guess you like

Origin blog.csdn.net/hongxue8888/article/details/105117500