Search code examples
javaandroidcjava-native-interface

Why can't C function pass right argument to java?


In my testing, I want to call Java from C and pass a long type argument, when I use long type, in the Java method, the argument passed in can't be gotten rightly, it is always 4294967297. But when I tried to use int type, everything got ok.Does anyone know what's wrong?

JAVA:

public static void test(long num) {
    Log.d("test", "xxxxxxxxxxx:%ld" + String.valueOf(num));
}

C:

void test_jni()
{
    long num = 5000;
    jclass theClass = (*currentJNIEnv)->FindClass(currentJNIEnv, "me/example/something/TestClass");
    if (NULL != theClass) {
        jmethodID mid = (*currentJNIEnv)->GetStaticMethodID(currentJNIEnv, theClass, "test", "(J)V");
        if (mid == 0) return;
        (*currentJNIEnv)->CallStaticVoidMethod(currentJNIEnv, theClass, mid, num);
    }
}

Solution

  • long in Java is always a 64-bit integer type, long in C may be a 32-bit integer type (at least on x86 32 bits linux). So they are different. That's why you get garbage.

    In C, use jlong instead of long, which is typedefed to a sufficiently long integer datatype.