NDK中开发中比较字符串是否相等,

  • Post author:
  • Post category:其他


/**

    利用Java的String类来完成字符编码转换

*/

char*  Jstring2CStr(JNIEnv*  env,jstring  jstr)
{
    LOGI("enter CStr2Jstring 1");
    char*   rtn   =   NULL;
    jclass   clsstring   =   (*env)->FindClass(env,"java/lang/String");
    jstring   strencode   =  (*env)->NewStringUTF(env,"GB2312");//转换成Cstring的GB2312,兼容ISO8859-1
    //jmethodID   (*GetMethodID)(JNIEnv*, jclass, const char*, const char*);第二个参数是方法名,第三个参数是getBytes方法签名
    //获得签名:javap -s java/lang/String:   (Ljava/lang/String;)[B
    jmethodID   mid   =   (*env)->GetMethodID(env,clsstring,"getBytes","(Ljava/lang/String;)[B");
    //等价于调用这个方法String.getByte("GB2312");
    //将jstring转换成字节数组
    LOGI("enter CStr2Jstring 2");
    //用Java的String类getByte方法将jstring转换为Cstring的字节数组
    jbyteArray  barr=   (jbyteArray) (*env)->CallObjectMethod(env,jstr,mid,strencode);
    LOGI("enter CStr2Jstring 3");
    jsize   alen   =   (*env)->GetArrayLength(env,barr);
    LOGI("enter CStr2Jstring 4");
    jbyte*   ba   =   (*env)->GetByteArrayElements(env,barr,JNI_FALSE);
    LOGI("alen=%d\n",alen);
    if(alen   >   0)
    {
        rtn   =   (char*)malloc(alen+1+128);
        LOGI("rtn address == %p",&rtn);//输出rtn地址
        memcpy(rtn,ba,alen);
        rtn[alen]=0;            //"\0"
    }
    (*env)->ReleaseByteArrayElements(env,barr,ba,0);
    return rtn;
}

/**
 * 字符验证
 */
JNIEXPORT jint JNICALL Java_com_org_vincent_javacallc_JNI_checkPwd
        (JNIEnv * env, jobject job, jstring js){
    const char *fromJava= Jstring2CStr(env,js);
    //服务器密码为1557
    LOGI("fromJava =%s",fromJava);
    char  *c="1557";
    int  resultCode;
    resultCode = strcmp(fromJava,c);
    LOGI("resultCode = %d",resultCode);
   // (*env)->ReleaseStringCritical(env,js,fromJava);
    if (resultCode==0)
        return 1;
    else
        return 0;
}

//第二个版本
JNIEXPORT jint JNICALL Java_com_org_vincent_javacallc_JNI_checkPwd
        (JNIEnv * env, jobject job, jstring js){

    LOGI("javaString==%s",(*env)->GetStringUTFChars(env,js,JNI_FALSE));
    //这里没有使用Jstring2CStr函数,使用了jni的接口方法GetStringUTFChars,但是用GetStringChars方法不行。
    const char *fromJava= (*env)->GetStringUTFChars(env,js,JNI_FALSE);
    //服务器密码为1557
    LOGI("fromJava =%s",fromJava);
    char  *c="1557";
    int  resultCode;
    resultCode = strcmp(fromJava,c);
    LOGI("resultCode = %d",resultCode);
    (*env)->ReleaseStringUTFChars(env,js,fromJava);
    if (resultCode==0)
        return 1;
    else
        return 0;
}



版权声明:本文为JQ_AK47原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。