JNI程序中的jstring返回 [英] jstring return in JNI program

查看:173
本文介绍了JNI程序中的jstring返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是JNI代码.

Java代码:

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);    
   }
}

string方法函数的Cpp方法:

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;    
 }

运行我的Java代码时.我得到下面的结果.

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

stringMethod: world

但是我在字符串后附加了字符串"world".与你好".我也在这里返回附加的字符串.但是,为什么我只得到世界"?不是"Hello 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?

推荐答案

这应该是这样做的方法....

this should be the way to do it....

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;        
}

这篇关于JNI程序中的jstring返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆