30

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?

1
  • 2
    The problem is elsewhere, your concatenation is perfectly valid: codepad.org/WWR4LzfV Commented Dec 11, 2012 at 22:26

2 Answers 2

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;        
}
Sign up to request clarification or add additional context in comments.

3 Comments

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...
Should (*env)->NewStringUTF(...) be env->NewStringUTF(...)?
@nn0p When using env functions in c, the statement is (*env)->Function(env, parameters). However in c++, this turns to: env->Function(parameters).
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()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.