我试图将char数组从
java传递给c.我用Google搜索实现它的方式.但是当我试图访问数组的值时,值不正确.
事实上,我试图给阵列一个角色.就像buffer [i] =’z’一样,结果在android中是正确的.
顺便说一句,我想要的值是rs232发送的值.来自rs232的值还可以.
有人告诉我使用bytearray.会有用吗?我害怕rs232的值无法存储到bytearray中….
Java的
public native int OpenPort(int portnum,int brates); public native int ClosePort(int portnum); public native int READ(char[] databuffer); public char[] buffer=new char[40]; int i; for(i=0;i<40;i++) buffer[i]='s'; //initialization OpenPort(16,9600); // A function to open the rs232 port while (i<1000) { READ(buffer); i++; }
JNI.c
JNIEXPORT jint JNICALL Java_com_example_ndk_Vehicles_READ(JNIEnv *env,jclass cls,jcharArray databuffer) { char tmp[40]; jchar *buffer=(*env)->GetCharArrayElements(env,databuffer,0); memset(tmp,sizeof(tmp)); PollComport(16,tmp,40); //will the problem here ? This function need a unsigned char[] //,but in the c program I wrote,char[] was ok for this. memcpy(buffer,40); (*env)->ReleaseCharArrayElements(env,buffer,0); return 0; }
解决方法
这是一个简单的例子
public native int play(String filename_main,String filename_prev,int main_x,int main_y,int main_width,int main_height,int preview_x,int preview_y,int preview_width,int preview_height);
映射到
int play(char* filename_main,char* filename_preview,int preview_height)
使用此JNI调用.
JNIEXPORT jint JNICALL Java_com_rtrk_demo_PELib_play(JNIEnv *env,jobject obj,jstring main_video,jstring prev_video,jint main_x,jint main_y,jint main_width,jint main_height,jint prev_x,jint prev_y,jint prev_width,jint prev_height) { LOGI("JNICALL - Java_com_rtrk_demo_PELib_play(filename)\n"); const char* utf_main_video = env->GetStringUTFChars(main_video,0); const char* utf_prev_video = env->GetStringUTFChars(prev_video,0); char* file_main_video = (char*) malloc(strlen(utf_main_video) * sizeof(char) +1); char* file_prev_video = (char*) malloc(strlen(utf_prev_video) * sizeof(char) +1); strcpy(file_main_video,utf_main_video); strcpy(file_prev_video,utf_prev_video); LOGI("JNICALL - filenames: %s\t%s\n",file_main_video,file_prev_video); env->ReleaseStringUTFChars(main_video,utf_main_video); env->ReleaseStringUTFChars(prev_video,utf_prev_video); LOGI("###JNICALL RET - Java_com_rtrk_demo_PELib_play(%s,%s)\n",file_prev_video); int retVal = play(file_main_video,file_prev_video,(int)main_x,(int)main_y,(int)main_width,(int)main_height,(int)prev_x,(int)prev_y,(int)prev_width,(int)prev_height); free(file_main_video); free(file_prev_video); return retVal; }