jbytearray转c++byte数组
jbyte * arrayBody = env->GetByteArrayElements(data,0); jsize theArrayLengthJ = env->GetArrayLength(data); BYTE * starter = (BYTE *)arrayBody;
//jbytearray strIn jbyte * olddata = (jbyte*)env->GetByteArrayElements(strIn, 0); jsize oldsize = env->GetArrayLength(strIn); BYTE* bytearr = (BYTE*)olddata; int len = (int)oldsize;
//nOutSize是BYTE数组的长度 BYTE pData[] jbyte *by = (jbyte*)pData; jbyteArray jarray = env->NewByteArray(nOutSize); env->SetByteArrayRegin(jarray, 0, nOutSize, by);
char* data = (char*)env->GetByteArrayElements(strIn, 0);
jstring WindowsTojstring(JNIEnv* env, char* str_tmp) { jstring rtn=0; int slen = (int)strlen(str_tmp); unsigned short* buffer=0; if(slen == 0) { rtn = env->NewStringUTF(str_tmp); } else { int length = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str_tmp, slen, NULL, 0); buffer = (unsigned short*)malloc(length*2+1); if(MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str_tmp, slen, (LPWSTR)buffer, length) > 0) { rtn = env->NewString((jchar*)buffer, length); } } if(buffer) { free(buffer); } return rtn; }
char* jstring互转
JNIEXPORT jstring JNICALL Java_com_explorer_jni_SambaTreeNative_getDetailsBy (JNIEnv *env, jobject jobj, jstring pc_server, jstring server_user, jstring server_passwd) { const char *pc = env->GetStringUTFChars(pc_server, NULL); const char *user = env->GetStringUTFChars(server_user, NULL); const char *passwd = env->GetStringUTFChars(server_passwd, NULL); const char *details = smbtree::getPara(pc, user, passwd); jstring jDetails = env->NewStringUTF(details); return jDetails; }
4. JNI开发中碰到的"error: request for member 'GetStringUTFChars' in something not a structure or union"
strTemp=env->GetStringUTFChars(env,str,NULL); 这句不能这么写 C语言里要写成 strTemp=(*env)->GetStringUTFChars(env,str,NULL); C++里 要这么写 strTemp= env->GetStringUTFChars(str,NULL); 这个还不是jni最难的,我认为JNI最难的是 数组类型参数值的传递(java传给C++或C++传给java),尤其是字符串数组传递。得动态开辟空间,传递后内存释放问题更闹心,搞不清哪个变量归java管不用释放,哪个归C++管需要手动释放。