在JNI中创建整数对象

时间:2016-11-14 19:06:04

标签: java c java-native-interface

我希望Integer对象从JNI返回到java层。调用NewObject(env, interger, init, rc)时,以下代码崩溃。创建Integer对象并返回它的正确方法是什么?

jint rc = 0;

jclass intClass = (*env)->FindClass(env, "java/lang/Integer");
if (intClass == NULL) {
    return NULL;
}
jmethodID init =  (*env)->GetMethodID(env, intClass, "intValue", "()I");
if (init == NULL) {
    return NULL;
}
jobject rc_obj = (*env)->NewObject(env, intClass, init, rc);
if (rc_obj == NULL) {
    return NULL;
}

return rc_obj;

谢谢!

1 个答案:

答案 0 :(得分:6)

试试这个:

jclass cls = (*env)->FindClass(env, "java/lang/Integer");
jmethodID midInit = (*env)->GetMethodID(env, cls, "<init>", "(I)V");
if (NULL == midInit) return NULL;
jobject newObj = (*env)->NewObject(env, cls, midInit, number);