ibm123
ibm123

Reputation: 1254

NDK, passing primitive data from c++ to java

I got a android project written in java which uses the ndk for some openGL stuff..

I got a cpp function that get's call and from there i want to call a java function

c++:

JNIEXPORT void JNICALL
Java_com_qualcomm_QCARSamples_ImageTargets_ImageTargetsRenderer_renderFrame(JNIEnv* env, jobject obj)
{
jclass activityClass = env->GetObjectClass(obj);

// Do something
char* argToPass = "Some string";
        jmethodID functionID = env->GetMethodID(activityClass,
                                                    "CallBack", "()V");
        env->CallObjectMethod(obj, functionID, 0); 
}

Java:

public  void CallBack(string arg){
 // Do sometihng
 }

Question is how to do i pass the argToPass argument to the java function

Thanks...

Upvotes: 0

Views: 2000

Answers (2)

hankystyles
hankystyles

Reputation: 511

See here for a detailed description about the calling java methods through jni.

Looks like you're method signature is wrong. The link above has a good description of how to determine your method signature. Here's what your GetMethodId call should look like:

jmethodID functionID = env->GetMethodID(
    activityClass,
    "CallBack", 
    "(Ljava/lang/String;)V");

Then when you call your method you'd do it like so:

env->CallVoidMethod(
    obj,
    functionID,
    env->NewStringUTF(argToPass));

Note that I used CallVoidMethod, since your return value in java is void.

Upvotes: 1

BitBank
BitBank

Reputation: 8735

To create a string that can be passed or returned to Java, use NewStringUTF():

JNIEXPORT jstring JNICALL Java_com_something_or_other_makeString(JNIEnv *env, jobject obj)
{
char *myString = "This is a test";
return (*env)->NewStringUTF(env, myString);
}

Upvotes: 0

Related Questions