William Seemann
William Seemann

Reputation: 3530

Issue with instance and class variable states when using JNI

I'm currently writing some Android code that uses JNI and I'm having difficulty how class and instance variables work. If I execute the following code I would expect the code to print a value of "18" but I always receive a value of "0". Can someone explain what I'm doing wrong?

// Java code

SampleClass sc = new SampleClass(18);
sc.printId() // returns 18, as expected
sc.nativePrintId() // returns 0, why?!

// Java Class

public class SampleClass
{ 
    private int mId = -1;        

    public FFmpegMediaPlayer(int id) {
        mId = id;
    }

    public void printId() {
        System.out.println("id: " + mId);
    }

    public native void nativePrintId();
}

// JNI C++ code

static void nativePrintId(JNIEnv* env, jobject thiz)
{
    jclass clazz = env->FindClass("wseemann/media/SampleClass");

    jmethodID printId = env->GetMethodID(clazz, "printId", "()V");

    env->CallVoidMethod(clazz, printId); // always prints zero?
 }

Upvotes: 1

Views: 124

Answers (1)

manuell
manuell

Reputation: 7620

You must pass the object, not the class, to CallVoidMethod.

Use:

env->CallVoidMethod(thiz, printId);

Also, you should get the class from the object, not from FindClass.

Use:

jclass clazz = env->GetObjectClass(thiz);

Upvotes: 2

Related Questions