java与C中的各种数据类型的传递是JNI的主要内容,其中字符串的传递相对其它基本类型的传递稍微困难些,在JNI中经常用到。
自定义对象的传递实际和String的传递类似。从网上找到的片断代码,改了一些内容。<br><br>static jstring stoJstring(JNIEnv* env, const char* pat)<br>{<br> jclass strClass = (*env)->FindClass(env, "Ljava/lang/String;");<br> jmethodID ctorID = (*env)->GetMethodID(env, strClass, "<init>", "([BLjava/lang/String;)V");<br> jbyteArray bytes = (*env)->NewByteArray(env, strlen(pat));<br> (*env)->SetByteArrayRegion(env, bytes, 0, strlen(pat), (jbyte*)pat);<br> jstring encoding = (*env)->NewStringUTF(env, "utf-8"); <br> return (jstring)(*env)->NewObject(env, strClass, ctorID, bytes, encoding);<br>}<br><br>static char* jstringTostring(JNIEnv* env, jstring jstr)<br>{<br> char* rtn = NULL;<br> jclass clsstring = (*env)->FindClass(env, "java/lang/String");<br> jstring strencode = (*env)->NewStringUTF(env, "utf-8");<br> jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B");<br> jbyteArray barr= (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid, strencode);<br> jsize alen = (*env)->GetArrayLength(env, barr);<br> jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);<br> if (alen > 0)<br> {<br> rtn = (char*)malloc(alen + 1);<br> memcpy(rtn, ba, alen);<br> rtn[alen] = 0;<br> }<br> (*env)->ReleaseByteArrayElements(env, barr, ba, 0);<br> return rtn;<br>}