JNI与C/C++数据类型的转换

字符数组与jbyteArray

jbyteArray转字符数组

1
2
3
4
int byteSize = (int) env->GetArrayLength(jbyteArrayData);  //jbyteArrayData是jbyteArray类型的数据
unsigned char* data = new unsigned char[byteSize + 1];
env->GetByteArrayRegion(jbyteArrayData, 0, byteSize, reinterpret_cast<jbyte*>(data));
data[byteSize] = '\0';

字符数组转jbyteArray

1
2
3
jbyte *jb =  (jbyte*) data;   //data是字符数组类型
jbyteArray jarray = env->NewByteArray(byteSize); //byteSize是字符数组大小
env->SetByteArrayRegion(jarray, 0, byteSize, jb);

字符数组与jstring

jstring转字符数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char* JstringToChar(JNIEnv* env, jstring jstr) {
if(jstr == NULL) {
return NULL;
}
char* rtn = NULL;
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("utf-8");
jmethodID mid = env->GetMethodID(clsstring, "getBytes",
"(Ljava/lang/String;)[B");
jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
jsize alen = env->GetArrayLength(barr);
jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
if (alen > 0) {
rtn = (char*) malloc(alen + 1);
memcpy(rtn, ba, alen);
rtn[alen] = 0;
}
env->ReleaseByteArrayElements(barr, ba, 0);
return rtn;
}

字符数组转jstring

1
2
3
4
5
6
7
8
9
jstring StrtoJstring(JNIEnv* env, const char* pat)
{
jclass strClass = env->FindClass("java/lang/String");
jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
jbyteArray bytes = env->NewByteArray(strlen(pat));
env->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);
jstring encoding = env->NewStringUTF("utf-8");
return (jstring)env->NewObject(strClass, ctorID, bytes, encoding);
}

或者直接使用NewStringUTF方法:

1
jstring jstr = env->NewStringUTF(str);

int与jint

jint与int的互转都可以直接使用强转,如:

1
jint i = (jint) 10;