saplingPro
saplingPro

Reputation: 21329

sending jstring from jni c code to a java function that receives string as an argument

How do I send a jstring from JNI C code to a Java function that receives a String as an argument ?

I have read about the functions like callVoidMethodA(....) but they do not accept anything such as a jstring.

Upvotes: 5

Views: 6131

Answers (2)

artyom.stv
artyom.stv

Reputation: 2164

You haven't mentioned the target class name and the target method signature. So consider, for example, java.lang.StringBuilder.append(java.lang.String) method.

// First lets assume you have already received the next variables
void foo( JNIEnv* env, jobject obj )
{
    // Call StringBuilder.append() method
}

Now you need the class name and the method signature (according to docs)

static char const StringBuilder_ClassName = "java/lang/StringBuilder";
static char const StringBuilder_append_MethodName = "append";
static char const StringBuilder_append_MethodSignature =
    "(Ljava/lang/String;)Ljava/lang/StringBuilder;";

To call java method from JNI code you should obtain jmethodID

static jclass StringBuilder_Class = 0;
static jmethodID StringBuilder_append_Method = 0;

void Init( JNIEnv* env )
{
     if( StringBuilder_Class == 0 ) {
         StringBuilder_Class = (*env)->FindClass( env, StringBuilder_ClassName );
         // TODO: Handle error if class not found
     }
     if( StringBuilder_append_Method == 0 ) {
         StringBuilder_append_Method = (*env)->GetMethodID( env, StringBuilder_Class,
             StringBuilder_append_MethodName, StringBuilder_append_MethodSignature );
         // TODO: Handle error if method not found
     }
}

void foo( JNIEnv* env, jobject obj )
{
    Init();
    char* str;
    // str = ...;
    jstring jString = (*env)->NewStringUTF( env, str );
    // Because StringBuild.append() returns object, you should call CallObjectMethod
    jobject ret = (*env)->CallObjectMethod( env, obj, jString );
    // Here you can release local references, i.e.
    // (*env)->DeleteLocalRef( env, ret );
    // (*env)->DeleteLocalRef( env, jString );
    // But it is not necessary. Local references are released automatically when
    // thread returns from JNI code to Java code.
    // So you can ignore the returned value and not to release the jString local
    // reference, i.e. just call
    // (*env)->CallObjectMethod( env, obj, jString );
}

Upvotes: 3

twid
twid

Reputation: 6686

JNIEXPORT jstring JNICALL 
 Java_Prompt_getLine(JNIEnv *env, jobject obj)
 {
     char *buf = "Hi !!!!";
     jstring jString = (*env)->NewStringUTF(env, buf);
     free(buf);
     return jString;
 }

Upvotes: 0

Related Questions