Java JNI 将 jstring 转换为 char *

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4181934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:24:35  来源:igfitidea点击:

JNI converting jstring to char *

javajava-native-interface

提问by Prasham

I have passed a URL string from Java to C code as jstringdata type through the use of JNI. And my library method needs a char *as url.

我已经通过jstring使用 JNI将 URL 字符串作为数据类型从 Java 传递到 C 代码。我的库方法需要一个char *as url。

How can I convert jstringin char *?

jstring该如何转换char *

P.S.: Is there any advantage of using jcharArray in C? (i.e. Passing char []instead of string in native method)

PS:在 C 中使用 jcharArray 有什么好处吗?(即char []在本地方法中传递而不是字符串)

采纳答案by Jason Rogers

Here's a a couple of useful link that I found when I started with JNI

这是我开始使用 JNI 时发现的一些有用链接

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

关于您的问题,您可以使用它

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

回答by kangear

Thanks Jason Rogers's answer first.

首先感谢杰森罗杰斯的回答。

In Android&& cppshould be this:

Android&& cpp 中应该是这样的:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

可以修复这个错误:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

1. 错误:'->' 的基操作数具有非指针类型 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

2.错误:没有匹配的函数调用'_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

3.错误:没有匹配的函数调用'_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

4.添加“env->DeleteLocalRef(nativeString);” 最后。