Search code examples
javajava-native-interface

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


Solution

  • 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.