我试图将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,0,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,tmp,40);
(*env)->ReleaseCharArrayElements(env, databuffer, buffer, 0);
return 0;
}
答案 0 :(得分: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 main_x, int main_y, int main_width, int main_height, int preview_x, int preview_y, int preview_width, 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_main_video, 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;
}
答案 1 :(得分:0)
因为允许GetCharArrayElements()创建Java数组的副本,而是指向副本的指针。在你的代码中,你传入null为指针到布尔值的参数,它会告诉你是否有一个副本:
jchar *buffer=(*env)->GetCharArrayElements(env,databuffer,0);
因此,您可能会在完成后丢弃的副本上进行操作。而不是GetCharArrayElements(),用C ++操作本地数组,并使用SetCharArrayRegion()来复制它们。