如何在JNI中将int转换为String(?)?
我有一个int []数组,我想在JNI中将它的每个元素转换为String (?),最后将它们连接成一个String (?)(包括逗号)。
例如:
// java code int testIntArray = new int[]{1, 2, 3}; String arrayString = ""; jni.constructArrayString(testIntArray, arrayString); // the print content should like this: 1,2,3 System.out.println("ArrayString: " + arrayString);
// jni code JNIEXPORT void JNICALL constructArrayString (JNIEnv *env, jobject obj, jintArray jArr, jstring jstr) { // to do sth. // code maybe like the follow jint *arr = env -> GetIntArrayElements(jArr, 0); int len = env -> GetArrayLength(jArr); char *c_str = env -> GetStringUTFChars(jstr, 0); if(c_str == NULL) { return; } for(int i = 0; i < len; i++){ // how to concatenate the arr[i], arr[i+1] and the comma ',' // and finally make the arrayString like the string: 1,2,3 ? } }
我知道,没有一种直接的方法可以将int-type转换为字符串类型的数据或其他东西,但应该可以在JNI中操作,并最终将它们连接成一个String !
如果很难处理void返回类型,只需更改它! Thanx,提前!
================================================== =========================新问题:
首先,感谢@Jorn Vernee回答这么多,这似乎是我应该采取的好方法。 但是,当我尝试这种方式时,有一个关于std :: stringstream的棘手问题。 好吧,即使实例化它也会使应用程序崩溃。 而且,遗憾的是我是JNI的新手,没有调试JVM运行时错误的崩溃问题的经验。 我检查了@Moe Bataineh的问题 ,看起来真的像我一样,但是它在Windows上应用了MiniGW或Cygwin我不知道的东西,所以它对我来说是无用的。
JNI中的代码是这样的:
#include "utils_JniInterface.h" #include #include #include #include using namespace std; #define TAG "JNI-Log" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) JNIEXPORT jstring JNICALL Java_utils_JniInterface_constructRGBArrayString (JNIEnv *env, jobject obj, jintArray jArr){ jint *arr = env -> GetIntArrayElements(jArr, 0); int len = env -> GetArrayLength(jArr); std::stringstream result; for(int i = 0; i < len; i++) { result << arr[i]; if(i < len - 1) { result < ReleaseIntArrayElements(jArr, arr, 0); return env -> NewStringUTF(result.str().data()); } // int[] a = {1,2,3} ⇒ String b = "1,2,3"
关于这个问题有什么好的想法或建议吗?
这非常直截了当:
JNIEXPORT jstring JNICALL Java_Main_callCPP(JNIEnv *env, jclass, jintArray ints) { jint* jints = env->GetIntArrayElements(ints, 0); int length = env->GetArrayLength(ints); std::stringstream result; for(int i = 0; i < length; i++) { result << jints[i]; if(i < length - 1) { result << ','; } } env->ReleaseIntArrayElements(ints, jints, JNI_ABORT); return env->NewStringUTF(result.str().data()); }
Java签名的位置是:
private static native String callCPP(int[] ints);
(当然,名称可以是你想要的任何东西)。 用法:
int[] ints = { 1, 2, 3 }; String result = callCPP(ints); System.out.println(result); // prints '1,2,3'
有用的链接: 关于android NDK中iostream的问题
使用std :: stringstream时 ,我也遇到以下错误;
致命错误:找不到’sstream’文件
#include
生成^ 1错误。
帮助我的解决方案是创建一个名为“ Application.mk ”的文件(注意:区分大小写)。 您需要添加的唯一一行是:
APP_STL:= stlport_static
将“ Application.mk ”文件放在“jni”文件夹中,这与“Android.mk”文件位于同一位置。 这在eclipse中对我有用,我可以认为它也适用于android studio。
这是一个替代方案的链接: Android ndk-build iostream:没有这样的文件或目录
希望这有助于@frank jorsn