基本数据类型转换
Java类型 别名 C++本地类型 字节(bit)
boolean jboolean unsigned char 8, unsigned
byte jbyte signed char 8
char jchar unsigned short 16, unsigned
short jshort short 16
int jint long 32
long jlong __int64 64
float jfloat float 32
double jdouble double 64
boolean jboolean unsigned char 8, unsigned
byte jbyte signed char 8
char jchar unsigned short 16, unsigned
short jshort short 16
int jint long 32
long jlong __int64 64
float jfloat float 32
double jdouble double 64
也就说基本数据类型就可以直接转换了 ,比较麻烦的是char * 和jstring类型的呼唤,查看jni.h
可以知道有如下方法:
jstring 转 char *
const char *nativeString = (*env)->GetStringUTFChars(env, javaString, 0);
// 使用nativeString
(*env)->ReleaseStringUTFChars(env, javaString, nativeString);
char * 转 jstring (未测试)
jstring jstr = (*env)->NewStringUTF(char *utf)
// // 使用jstr
(*env)->ReleaseStringUTFChars(env, jstr, utf);
String 转 jstring
String str = "test";
jstring jstr= m_jEnv->NewStringUTF(str.utf8().data());
//删除java对象 jstr
pEnv->DeleteLocalRef(jstr);
static jstring stoJstring(JNIEnv* env, const char* pat)
{
jclass strClass = (*env)->FindClass(env, "Ljava/lang/String;");
jmethodID ctorID = (*env)->GetMethodID(env, strClass, "<init>", "([BLjava/lang/String;)V");
jbyteArray bytes = (*env)->NewByteArray(env, strlen(pat));
(*env)->SetByteArrayRegion(env, bytes, 0, strlen(pat), (jbyte*)pat);
jstring encoding = (*env)->NewStringUTF(env, "utf-8");
return (jstring)(*env)->NewObject(env, strClass, ctorID, bytes, encoding);
}
static char* jstringTostring(JNIEnv* env, jstring jstr)
{
char* rtn = NULL;
jclass clsstring = (*env)->FindClass(env, "java/lang/String");
jstring strencode = (*env)->NewStringUTF(env, "utf-8");
jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr= (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid, strencode);
jsize alen = (*env)->GetArrayLength(env, barr);
jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);
if (alen > 0)
{
rtn = (char*)malloc(alen + 1);
memcpy(rtn, ba, alen);
rtn[alen] = 0;
}
(*env)->ReleaseByteArrayElements(env, barr, ba, 0);
return rtn;
}
很多方法可以参考jni.h
搜索到这个人的博客,总结的不错
http://blog.csdn.net/ostrichmyself/article/details/4557851
http://blog.csdn.net/popop123/article/details/1511180