JNI常用型別轉換

大頭呆發表於2019-03-03

記錄下JNI常用型別轉換:

string轉jstring

std::string hello = "Hello from C++";
jstring jHello=env->NewStringUTF(hello.c_str());
複製程式碼

char*轉jstring

jstring util_char_to_jstring(JNIEnv *env, const char *pat) {
    //定義java String類 strClass
    jclass strClass = (env)->FindClass("java/lang/String");
    //獲取String(byte[],String)的構造器,用於將本地byte[]陣列轉換為一個新String
    jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
    //建立byte陣列
    jbyteArray bytes = (env)->NewByteArray(strlen(pat));
    //將char* 轉換為byte陣列
    (env)->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte *) pat);
    // 設定String, 儲存語言型別,用於byte陣列轉換至String時的引數
    jstring encoding = (env)->NewStringUTF("utf-8");
    //將byte陣列轉換為java String,並輸出
    return (jstring) (env)->NewObject(strClass, ctorID, bytes, encoding);
}
複製程式碼

jstring轉char*:

void util_jstring_to_char(JNIEnv *env, jstring jstr, char *result) {
    if (env == NULL || jstr == NULL) {
        return;
    }
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("utf-8");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
    jsize alen = env->GetArrayLength(barr);
    jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE);
    if (alen > 0) {
        memcpy(result, ba, alen);
        result[alen] = 0;
    }
    env->ReleaseByteArrayElements(barr, ba, 0);
}

複製程式碼

char*是可以直接賦值給string的:

 string s;
 char *p = "hello";//直接賦值
 s = p;
複製程式碼

int轉string

string util_int_to_string(unsigned int n) {
    string sResult;
    stringstream ssTmp;
    ssTmp << n;
    ssTmp >> sResult;
    return sResult;
}
複製程式碼

JByteArray轉char*

char *convertJByteArrayToChar(JNIEnv *env, jbyteArray byYUV1_) {

    jbyte *bytes = env->GetByteArrayElements(byYUV1_, 0);
    int arrayLength = env->GetArrayLength(byYUV1_);
    char *chars = new char[arrayLength + 1];
    memset(chars, 0x0, arrayLength + 1);
    memcpy(chars, bytes, arrayLength);
    chars[arrayLength] = 0;
    env->ReleaseByteArrayElements(byYUV1_, bytes, 0);

    return chars;
}
複製程式碼

char*轉JByteArray

jbyteArray util_char_to_jbyteArray(JNIEnv *env, char *data, int length) {
    jbyte *by = (jbyte *) data;
    jbyteArray jarray = env->NewByteArray(length);
    env->SetByteArrayRegion(jarray, 0, length, by);
    return jarray;
}
複製程式碼

相關文章