Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jstring return in JNI program

This is JNI code.

Java code:

public class Sample1 {
 
    public native String stringMethod(String text);
    
    public static void main(String[] args)
    {
       System.loadLibrary("Sample1");
       Sample1 sample = new Sample1();
    
       String  text   = sample.stringMethod("world");
    
       System.out.println("stringMethod: " + text);    
   }
}

Cpp Method for stringMethod function:

JNIEXPORT jstring JNICALL Java_Sample1_stringMethod
   (JNIEnv *env, jobject obj, jstring string) {
   
 const char *name = env->GetStringUTFChars(string, NULL);//Java String to C Style string
 char msg[60] = "Hello ";
 jstring result;

 strcat(msg, name);
 env->ReleaseStringUTFChars(string, name);
 puts(msg);
 result = env->NewStringUTF(msg); // C style string to Java String
 return result;    
 }

When running my java code. I got the result below.

stringMethod: world

But I appended the string "world" with "Hello ". I'm also returning here the appended string. But why I'm getting only "world" not "Hello World". Really I confused with this code. What should I do to get the result with appended string?

like image 722
Smith Dwayne Avatar asked Sep 05 '25 05:09

Smith Dwayne


1 Answers

JNIEXPORT jstring JNICALL Java_Sample1_stringMethod
    (JNIEnv *env, jobject obj, jstring string) 
{    
    const char *name = (*env)->GetStringUTFChars(env,string, NULL);
    char msg[60] = "Hello ";
    jstring result;
    
    strcat(msg, name);  
    (*env)->ReleaseStringUTFChars(env,string, name);   
    puts(msg);            
    result = (*env)->NewStringUTF(env,msg); 
    return result;        
}
like image 69
user4302170 Avatar answered Sep 07 '25 21:09

user4302170