我在Android中编写了一个c-jni函数,我在创建Long-object时遇到了问题。我成功调用了构造函数,但是当我用longValue读取对象的值时,我得到了错误的结果。
jmethodID longConstructor;
jmethodID longGetLongValue;
jclass cls;
jobject obj;
// Create a object of type Long.
cls = (*env)->FindClass(env,"java/lang/Long");
longConstructor = (*env)->GetMethodID(env,cls,"<init>","(J)V");
obj = (*env)->NewObject(env, cls, longConstructor, 4242);
// Get the value by calling the function longValue.
longGetLongValue= (*env)->GetMethodID(env,cls,"longValue","()J");
long return_long_value = (*env)->CallLongMethod(env, obj, longGetLongValue);
// Log the result.
LOGD("%li", return_long_value);
我希望上面的代码会在日志中打印4242,但是日志中打印的值是1691768.
有没有人知道为什么4242没有写入日志?
答案 0 :(得分:3)
&lt; jni.h&gt; 声明
typedef long long jlong; /* signed 64 bits */
因此,这是修复:
obj = (*env)->NewObject(env, cls, longConstructor, (jlong)4242); // or 4242ll
longGetLongValue= (*env)->GetMethodID(env,cls,"longValue","()J");
long return_long_value = (*env)->CallLongMethod(env, obj, longGetLongValue);
jlong return_jlong_value = (*env)->CallLongMethod(env, obj, longGetLongValue);
__android_log_print(ANDROID_LOG_DEBUG, "test", "native t = %ld", return_long_value);
__android_log_print(ANDROID_LOG_DEBUG, "test", "native t = %lld", return_jlong_value);
答案 1 :(得分:1)
如果你看一下JNI映射类型,C中的long等同于jint,因此我认为你应该使用java / lang / Integer而不是java / lang / Long。
// Create a object of type Integer
jclass cls = (*env)->FindClass(env, "java/lang/Integer");
jmethodID constructorId = (*env)->GetMethodID(env, cls, "<init>", "(I)V");
jobject o = (*env)->NewObject(env, cls, constructorId, 4242);
// Get the value by calling the function intValue.
jmethodID intValueMethodId = (*env)->GetMethodID(env, cls, "intValue", "()I");
long val = (*env)->CallIntMethod(env, obj, intValueMethodId);
// Log the result.
LOGD("%d", val);