JNI中查找類,訪問類的域

查找類:

jclass FindClass(JNIEnv *env, const char *name);

訪問類的域:

jfieldID GetFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);


NativeType Get<type>Field(JNIEnv *env, jobject obj,
jfieldID fieldID);


void Set<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID,
NativeType value);


看例子:

package com.example.witness.myapplication;

/**
 * Created by witness on 15-10-17.
 */
public class Point {
    int x;
    int y;
}


package com.example.witness.myapplication;

/**
 * Created by witness on 15-10-17.
 */
public class Detector {
    public native Point reverse(Point p);
}

頭文件:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_witness_myapplication_Detector */

#ifndef _Included_com_example_witness_myapplication_Detector
#define _Included_com_example_witness_myapplication_Detector
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_witness_myapplication_Detector
 * Method:    reverse
 * Signature: (Lcom/example/witness/myapplication/Detector/Point;)Lcom/example/witness/myapplication/Detector/Point;
 */
JNIEXPORT jobject JNICALL Java_com_example_witness_myapplication_Detector_reverse
  (JNIEnv *, jobject, jobject);

#ifdef __cplusplus
}
#endif
#endif


源文件:

#include "com_example_witness_myapplication_Detector.h"

JNIEXPORT jobject JNICALL Java_com_example_witness_myapplication_Detector_reverse
        (JNIEnv *env, jobject obj1, jobject point){
        jclass cla = (*env)->FindClass(env, "com/example/witness/myapplication/Point");
        jfieldID xId = (*env)->GetFieldID(env, cla, "x", "I");
        jfieldID yId = (*env)->GetFieldID(env, cla, "y", "I");
        jint x = (*env)->GetIntField(env, point, xId);
        jint y = (*env)->GetIntField(env, point, yId);
        (*env)->SetIntField(env, point, xId, y);
        (*env)->SetIntField(env, point, yId, x);
        return point;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章