简体   繁体   English

Android:将浮点值从Java传递到JNI总是NaN

[英]Android: Passing float values from Java to JNI is always NaN

Short version: I can pass double values from Java to C++ using a JNI jdouble. 简短版:我可以使用JNI jdouble将double值从Java传递到C ++。 However, when I use floats, the C++ jfloat parameter is always NaN. 但是,当我使用浮点数时,C ++ jfloat参数始终为NaN。

Longer version: I'm modifying the hello-gl2 Android sample for VS 2015 which draws a triangle ( https://code.msdn.microsoft.com/hello-gl2-android-3b61896c ), adding a simple function to rotate the triangle. 较长版本:我正在修改VS 2015的hello-gl2 Android示例,该示例绘制了一个三角形( https://code.msdn.microsoft.com/hello-gl2-android-3b61896c ),添加了一个简单的函数来旋转三角形。

In gl_code.cpp: 在gl_code.cpp中:

extern "C" {
    JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_updateAngle(JNIEnv * env, jfloat dAngle);
};
JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_updateAngle(JNIEnv * env, jfloat dAngle)
{
    __android_log_print(ANDROID_LOG_DEBUG, "DEBUG", "updateAngle: %f", dAngle);
    rotationAngle += dAngle;
}

And in GL2JNILib.java: 在GL2JNILib.java中:

public class GL2JNILib {
    public static native void updateAngle(float dAngle);
}

And this is all called from the GL2JNIView.java: 这全部是从GL2JNIView.java调用的:

GL2JNILib.updateAngle(0.5f);

The VS debugger shows the value of jfloat dAngle to be nan(3b52bc) no matter what value I pass from Java, logcat shows "nan" and OpenGL confirms this by drawing nothing. VS调试器将jfloat dAngle的值显示为nan(3b52bc),无论我从Java传递什么值,logcat都显示“ nan”,而OpenGL通过不画任何东西来确认这一点。

I'm running on a Nexus 9 hardware device. 我在Nexus 9硬件设备上运行。 When using the Nexus_5_API_22_x86 emulator, I seem to get many different values, sometimes NaN, even though I'm always passing in 0.5f. 使用Nexus_5_API_22_x86仿真器时,即使我总是传入0.5f,我似乎也会得到许多不同的值,有时甚至是NaN。 If I replace "jfloat" with "jdouble" and "float" with "double" in all the code above, everything works fine on the device and emulator. 如果我在以上所有代码中将“ jfloat”替换为“ jdouble”,将“ float”替换为“ double”,则在设备和仿真器上一切正常。

What am I doing wrong? 我究竟做错了什么? Thanks!! 谢谢!!

You are missing the 2nd parameter in the native method: jclass . 您缺少本机方法jclass的第二个参数。 Your method signature in C should be: 您在C中的方法签名应为:

JNIEXPORT void JNICALL
    Java_com_android_gl2jni_GL2JNILib_updateAngle(JNIEnv *env,
                                                  jclass classz,
                                                  jfloat dAngle);

The 2nd parameter is a jclass because your method is static . 第二个参数是jclass因为您的方法是static If it were an instance method for the class then the 2nd parameter would be a jobject (the this for the object.) You might consider using the "javah" tool to help you generate method signatures. 如果它是该类的实例方法,则第二个参数将是一个jobject (对象的this )。您可以考虑使用“ javah”工具来帮助您生成方法签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM