28

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?

dustin2022
  • 182
  • 2
  • 18
Smith Dwayne
  • 2,675
  • 8
  • 46
  • 75

2 Answers2

23
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;        
}
spongebob
  • 8,370
  • 15
  • 50
  • 83
user4302170
  • 246
  • 3
  • 3
  • 3
    Well, the only difference that I see between your code and the author's code is that he is using C++ syntax for JNI and you C syntax for JNI... – gokan Oct 11 '15 at 23:50
  • 7
    Should `(*env)->NewStringUTF(...)` be `env->NewStringUTF(...)`? – nn0p Nov 25 '15 at 13:56
  • 10
    @nn0p When using `env` functions in c, the statement is `(*env)->Function(env, parameters)`. However in c++, this turns to: `env->Function(parameters)`. – agastalver Nov 07 '16 at 13:02
0

There are several ways but the best I got by converting const char * to c++ string and then to jbyteArray, and its easy to conversion of byteArray to UTF-8 on java side.

C++ side:

const char* string = propertyValue;
std::string str = string;

jbyteArray array = env->NewByteArray(str.length());
env->SetByteArrayRegion(array,0,str.length(),(jbyte*)str.c_str());


return array;

Java/kotlin side:

String((array), Charset.defaultCharset()))
PunyCode
  • 373
  • 4
  • 18
vijaycaimi
  • 317
  • 1
  • 2
  • 6