HardCoder
HardCoder

Reputation: 3036

Calling a Java function from C++ on Android over JNI

I am calling C++ from Android with JNI and so far it works. Now I need in that C++ function some functionality from Java and try to call back to Java from C++. I checked various solutions on stackoverflow and other sources on the net but I somehow just couldn't get it working.

I always get the following Exception "W/dalvikvm(358): JNI WARNING: can't call Lcom/main/Main;.message on instance of Lcom/main/Main;"

Can anyone give me any advice on this ? Did I miss something, oversee something or have just plain wrong code ?

Here is the Java part that I want to call from C++:

public class Main extends Activity  
{   
    public  native  String  JNIInit();

    String message(String text)
    {   text = text + "from java";
        return text;
    }
    .
    .
}

This is the C++ function that I can successfully call from Java but from which I cannot call back to Java:

extern "C" JNIEXPORT jstring JNICALL Java_com_main_Main_JNIInit(JNIEnv* env, jobject obj)
{   jstring jstr = env->NewStringUTF("From jni");
    jclass cls = env->FindClass("com/main/Main");
    jmethodID method = env->GetMethodID(cls, "message", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = env->CallObjectMethod(obj, method, jstr);
    return env->NewStringUTF(str);
}

PS: I know there are several threads on this topic here, but I couldn't get it working anyway. There must be something that I just miss, and I simply can't figure out what that is.

Upvotes: 2

Views: 6913

Answers (2)

Pavan
Pavan

Reputation: 1247

Instead of using FindClass, can you try using: (*env)->GetObjectClass(env, obj);

Upvotes: 2

user1203673
user1203673

Reputation: 1015

you have use create an empty string in c++ and also pass the empty string from java from the method

 jString pSrc = (*env)->GetString(env,source, 0);

// Here source is the empty string u are passing from the java method now u copy the string into source

 (*env)->String(env, source, pSrc , 0);

and in the end use

(*env)->ReleaseString(env,source, pSrc , 0);

Upvotes: -1

Related Questions