Hien Nguyen
Hien Nguyen

Reputation: 764

Cannot call from C to Java by using JNI

I can make the java code call to jni, but I meet the trouble when calling from jni to java, please help me by seeing the below code and result

In java:

public class SocketClient {
private native void nativeInit();

public void Init()
{
    nativeInit();
}
.........
    public boolean IsConnected()
    {
        Log.i("Test", "Hien public boolean IsConnected()");
        return _is_connected;
    }
.......

I make a call to Init method

SocketClient socketClient = new SocketClient();
socketClient.Init();

At Jni:

JNIEXPORT void Java_SocketClient_nativeInit (JNIEnv* env, jobject obj)
{
    LOG_INFO("Hien2 Java_SocketClient_nativeInit at jni layer");
    jclass cls = (*env)->GetObjectClass(env, obj);
    jmethodID mid = (*env)->GetMethodID(env, cls, "IsConnected", "()Z");
    int temp = (*env)->CallBooleanMethod(env, cls, mid);
    LOG_INFO("Hien3 temp=%d", temp);
}

The result output is below:

Hien2 Java_SocketClient_nativeInit at jni layer
Hien3 temp=168

The code in IsConnected() not be called !!!

Upvotes: 1

Views: 353

Answers (2)

SplinterReality
SplinterReality

Reputation: 3410

Your code needs a slight revision:

int temp = (*env)->CallBooleanMethod(env, obj, mid);

When calling the java method itself, you need to call the object, not the class. Check the function definitions carefully.

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223183

You are invoking CallBooleanMethod on the wrong object---the class object doesn't have an IsConnected method! It should be:

(*env)->CallBooleanMethod(env, obj, mid);

Upvotes: 1

Related Questions