Search code examples
androidandroid-ndkjava-native-interface

Why does this simple JNI object construction cause a VM abort and SIGSEGV?


Class:

package com.example.foo;

public class Dummy
{
    int value;

    public Dummy(int value)
    {
        this.value = value;
    }   
}

JNI snippet:

jclass class = (*jni_env)->FindClass(jni_env, "com/example/foo/Dummy");
jmethodID constructor = (*jni_env)->GetMethodID(jni_env, class, "<init>", "(I)V");
jobject object = (*jni_env)->NewObject(jni_env, constructor, 0);

LogCat output:

09-03 11:02:02.937: W/dalvikvm(2179): Invalid indirect reference 0x44e9cf80 in decodeIndirectRef
09-03 11:02:02.937: E/dalvikvm(2179): VM aborting
09-03 11:02:02.937: A/libc(2179): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 2179

Solution

  • NewObject() expects the class object pointer as the second parameter. The constructor method ID is the third parameter. Reformulate like this:

    jobject object = (*jni_env)->NewObject(jni_env, class, constructor, 17); 
    

    Where 17 is the argument to the constructor.