Android Java JNI和C Char数组无法识别该值

我试图将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;
}

相关文章

以下为个人理解,如错请评 CE: 凭据加密 (CE) 存储空间, 实际路径/data/user_ce/ DE: 设备加密 (DE) 存...
转载来源:https://blog.csdn.net/yfbdxz/article/details/114702144 用EventLog.writeEvent打的日志(或...
事件分发机制详解 一、基础知识介绍 1、经常用的事件有:MotionEvent.ACTION_DOWN,MotionEvent.ACTION...
又是好久没有写博客了,一直都比较忙,最近终于有时间沉淀和整理一下最近学到和解决的一些问题。 最近进...
Android性能优化——之控件的优化 前面讲了图像的优化,接下来分享一下控件的性能优化,这里主要是面向...
android的开源库是用来在android上显示gif图片的。我在网上查了一下,大家说这个框架写的不错,加载大的...