[JNI] Cache domain ID (Filed ID) and method ID (Method ID)

The following examples illustrate the possible bugs that do not cache the domain ID:

class C {
    private int i;
    native void f();
}

(1)Do not cache domain ID:

1) Get the class of the object, GetObjectClass.

2) Find out the field ID of variable i, GetFieldID.

3) Get the field value based on the field ID, GetIntField.

// No field IDs cached.
JNIEXPORT void JNICALL Java_C_f(JNIEnv *env, jobject this) {
    jclass cls = (*env)->GetObjectClass(env, this);
    jfieldID fid = (*env)->GetFieldID(env, cls, "i", "I");
    int ival = (*env)->GetIntField(env, this, fid);
}

If we define a subclass D of class C and declare a variable i in class D, problems will arise:

// Trouble in the absence of ID caching
class D extends C {
    private int i;
    D() {
        f();         // inherited from C
    }
}

When the constructor of D calls C's interface f, the jobject parameter in the native interface Java_C_f is the object of D, cls points to class D, and fid represents Di. So the value in ival is Di instead of Ci. This may not be what we want.

 

How to solve?

(2) Cache domain ID:

The solution is to cache the corresponding domain ID when you determine which class to use. See the following code:

// Version that caches IDs in static initializers
class C {
    private int i;
    native void f();
    private static native void initIDs();
    static {
        initIDs();         // Call an initializing native method
    }
}

static jfieldID FID_C_i;        //缓存域ID
JNIEXPORT void JNICALL Java_C_initIDs(JNIEnv *env, jclass cls) {
    /* Get IDs to all fields/methods of C that native methods will need. */
    FID_C_i = (*env)->GetFieldID(env, cls, "i", "I");
}

JNIEXPORT void JNICALL Java_C_f(JNIEnv *env, jobject this) {
    int ival = (*env)->GetIntField(env, this, FID_C_i);
    /* ival is always C.i, not D.i */
}

The domain ID is cached in the static method initIDs of class C. This ensures that FID_C_i caches the domain of the C variable i.

 

Reference materials:

[1]The Java™ Native Interface Programmer’s Guide and Specification.pdf

 

Guess you like

Origin blog.csdn.net/u012906122/article/details/103830667