JNI converting jstring to char *

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

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

How can I convert jstring in char * ?

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

回答1:

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

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(env, javaString, 0);     // use your string     (*env)->ReleaseStringUTFChars(env, javaString, nativeString); }


回答2:

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, JNI_FALSE);  // use your string  env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

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

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

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

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



转载请标明出处:JNI converting jstring to char *
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!