简体   繁体   中英

Instantiate Java class from JNI

I need to create an instance of a Java class in my native code. To do it, I am using the following C code:

jobject Java_com_mypackage__myClass_myMethod(JNIEnv* env, jobject thiz, jint index){
    int fd = pDevs[index].ufds.fd; // fd = open(....); it's a input/eventX file.
    jclass class = (*env)->FindClass(env,"com/mypackage/ClassName");
    jmethodID mid = (*env)->GetMethodID(env,class,"<init>","(Ljava/lang/String;)V");
    return (*env)->NewObject(env,class,mid,(*env)->NewStringUTF(env, pDevs[index].device_path));
}

But when I invoke myMethod, I keep getting fatal signal 11 (SIGSEGV). Is the code wrong?

You should use logging/debbuger to find place where segmentation fault happenned. The easiest way is to use android logging system as described here

jclass class = (*env)->FindClass(env,"com/mypackage/ClassName");
if(class == null)
{
  __android_log_print(ANDROID_LOG_VERBOSE, "TAG", "class is null");
}

For example if ClassName is an inner class of some activity you should use com/mypackage/ActivityName#ClassName instead of com/mypackage/ClassName. But I can only guess before you provide your logs.

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