Search code examples
androidandroid-ndkjava-native-interface

Bad values being pass in android jni calls


This is driving me crazy! I'm making a library with ndk, the linking was fine but I find that, when calling a method, the value of the argument passed to the corresponding c function is incorrect.

My java class is as follows

package ccme.usernet.love;
class LovePlayerEngine {
    static {
        System.loadLibrary("loveplayer");
    }
    public static native void init(int id);
}

And my C file is as follows:

#include <jni.h>
#include <android/log.h>

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "TEST", __VA_ARGS__))

JNIEXPORT void JNICALL Java_ccme_usernet_love_LovePlayerEngine_init(JNIEnv *env, jint id)
{
    LOGI("INIT with id %d\n", id);
}

The compiling and library linking was fine and the app was running. But when I called LovePlayerEngine.init(0); somewhere in my java code, I get some bad values such as 1079062016 which is not stable and will change on different runs.

My other tests such as passing variables instead of constants or passing a String all failed in getting unexpected values.

Anyone has got any clue of where the problem could be? This is sickin me, I've never encountered this in my former ndk projects.


Solution

  • You're missing a parameter in your call. It should be JNIEXPORT void JNICALL Java_ccme_usernet_love_LovePlayerEngine_init(JNIEnv *env, jobject obj, jint id)

    The missing parameter means you're using the object as the int value by mistake.