在JNI中从简单中获取Number的简单方法?

时间:2014-02-22 17:56:49

标签: java c++ java-native-interface

我想从C调用一个带有参数T extends Number的java方法。我知道java默认为你自动代替这些类型,但是当我尝试在JNI调用中传递floatjfloat时,我收到以下错误:

FATAL ERROR in native method: Bad JNI oop argument

是否有一种简单的方法可以生成Number java类或使用JNI将其传递给C语言的Java方法参数而无需关心实际的基元类型?

1 个答案:

答案 0 :(得分:0)

给定Java类

class CC {
    static void callbackMethod(Number number) {
        Log.i("callbackMethod", "arg = " + number);
    }
}

您可以使用native.c

#include <jni.h>

jclass floatClass = (*env)->FindClass(env, "java/lang/Float");
jmethodID floatConstructor = (*env)->GetMethodID(env, floatClass, "<init>", "(F)V");
jobject floatObj = (*env)->NewObject(env, floatClass, floatConstructor, (jfloat)1.23);

jclass callbackClass = (*env)->FindClass(env, "CC");
jmethodID callback = (*env)->GetMethodID(env, callbackClass, "callbackMethod", "(java/lang/Object)V");
(*env)->CallVoidMethod(env, callbackClass, callback, floatObj);