tags:

views:

247

answers:

1

Hi!

I am writing a c-jni function in Android, and I am having problems with creating a Long-object. I have succeeded in calling the constructor, but when I read the value of the object with longValue, I get the wrong result.

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);

I would expect that the above code would print 4242 in the log, however the value that is printed in the log is 1691768.

Does anybody have an idea on why 4242 is not written in the log?

A: 

If you look at JNI mapping types, long in C is equivalent to jint therefore I think you should use java/lang/Integer instead of 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);
Jedd