android jni jbyteArray和char*互相转换


jstring charToJString(JNIEnv *env, char *pat) {
    jclass strClass = env->FindClass("java/lang/String");
    jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
    jbyteArray bytes = env->NewByteArray(strlen(pat));
    env->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte *) pat);
    jstring encoding = env->NewStringUTF("utf-8");
    return (jstring) env->NewObject(strClass, ctorID, bytes, encoding);
}

jbyteArray charToJByteArray(JNIEnv *env, unsigned char *buf, int len) {
//    size_t len = strlen(reinterpret_cast<const char *>(buf));
    jbyteArray array = env->NewByteArray(len);
    env->SetByteArrayRegion(array, 0, len, reinterpret_cast<jbyte *>(buf));
    return array;
}

char *jByteArrayToChar(JNIEnv *env, jbyteArray buf) {
    char *chars = NULL;
    jbyte *bytes;
    bytes = env->GetByteArrayElements(buf, 0);
    int chars_len = env->GetArrayLength(buf);
    chars = new char[chars_len + 1];
    memset(chars, 0, chars_len + 1);
    memcpy(chars, bytes, chars_len);
    chars[chars_len] = 0;
    env->ReleaseByteArrayElements(buf, bytes, 0);
    return chars;
}



extern "C"
JNIEXPORT jobject JNICALL
Java_com_qtec_keyservice_KeyServiceJni_getQKey(JNIEnv *env, jclass clazz, jlong ul_handle,
                                               jint ui_key_len, jstring uc_key_id, jstring uc_key) {
    ULONG ulHandle = static_cast<ULONG>(ul_handle);
    UINT uiKeyLen = static_cast<UINT>(ui_key_len);
    unsigned char *cUcKeyId = (unsigned char *) env->GetStringUTFChars(uc_key_id, 0);
    unsigned char *cUcKey = (unsigned char *) env->GetStringUTFChars(uc_key, 0);

    LOGI("INFO———— getQKey start +++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    LOGI("INFO———— ulHandle = %lu", ulHandle);
    LOGI("INFO———— uiKeyLen = %d", uiKeyLen);
    LOGI("INFO———— cUcKeyId =  %s", cUcKeyId);
    LOGI("INFO———— cUcKey = %s", cUcKey);

    jint result = QTEC_SAF_GetQKey(ulHandle, uiKeyLen, cUcKeyId, cUcKey);


    for (int i = 0; i < 32; ++i) {
        LOGI("keyId %x", cUcKeyId[i]);
    }

    for (int i = 0; i < 32; ++i) {
        LOGI("key %x", cUcKey[i]);
    }

    jbyteArray jKeyId = charToJByteArray(env, cUcKeyId, 16);
    jbyteArray jKey = charToJByteArray(env, cUcKey, uiKeyLen);

    jclass resultClass = env->FindClass("com/qtec/keyservice/KeyResult");

    jmethodID constructMethod = env->GetMethodID(resultClass, "<init>", "(I[B[B)V");

    jobject keyResult = env->NewObject(resultClass, constructMethod, result, jKeyId, jKey);

    LOGI("INFO———— getQKey end +++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    return keyResult;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值