简体   繁体   中英

Java, JNI and Class declarations

Can any JNI expert explain the following situation, as i cannot wrap my head around the issue.

Say we have this class:

public class MyClass {
    static {
        System.loadLibrary("recorder");
    }

    private native long function1();    
    private native void function2();

    private void callback() {

    }

    public static void main(String[] args) throws Exception {
        MyClass obj1 = new MyClass();
        obj1.function1();
    }

}

in JNI (C):

JNIEXPORT jstring JNICALL function1(JNIEnv *env, jobject object) {
   jclass cls = (*env)->GetObjectClass(env, object);
   jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "()V");

   if (mid != NULL) {
        (*env)->CallVoidMethod(env, object, mid);
   }
}

This works fine, however, if instead of

private native long function1();

i declare

private static native long function1();

the call from JNI to Java fails complaining it cannot find the function callback in Java.

Thanks

For static native method the second argument in native code should not be the jobject but jclass .

But you should rather generate c headers with javah tool rather than writing them manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM