我有一个int[ ]数组,我想将它的每个元素转换为String(?) in JNI,最后将它们连接为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 into 字符串类型数据或其他东西,但应该可以在JNI,并将它们连接为String终于!
如果很难做到void返回类型,改一下就可以了!提前致谢!
=================================================== =========================
新问题:
首先,非常感谢@Jorn Vernee 的回答,这似乎是我应该采取的好方法。然而,当我尝试这种方式时,出现了一个棘手的问题std::字符串流。好吧,即使实例化它也会使应用程序崩溃。而且,遗憾的是我是新手JNI,没有调试 JVM 运行时错误导致的崩溃问题的经验。我查过@Moe Batainehquestion https://stackoverflow.com/questions/39709501/c-jni-crashes-hangs-when-doing-any-io-streams这看起来真的很像我,但是它在 Windows 上应用MiniGW or Cygwin有些事我不知道,所以对我来说很无助。
JNI 中的代码如下:
#include "utils_JniInterface.h"
#include <android/log.h>
#include <string.h>
#include <iostream>
#include <sstream>
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 << ',';
}
}
env -> ReleaseIntArrayElements(jArr, arr, 0);
return env -> NewStringUTF(result.str().data());
}
// int[] a = {1,2,3} ⇒ String b = "1,2,3"
对于这个问题有什么好的想法或者建议吗?