H
H
hHup2018-04-05 16:18:08
Java
hHup, 2018-04-05 16:18:08

How to return a String from a jni method?

I work in java with JNI, from a C++ method, I should get a string, but how to implement this if C++ sends char [] and java accepts String ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-04-05
@TopMetaFizick

JNIEXPORT jstring JNICALL Java_Test_saySomething(JNIEnv *env, jobject obj, jstring jStr) {
    // Получаем указатель на массив символов String
    const char *cStr = (*env)->GetStringUTFChars(env, jStr, NULL);
    if (cStr == NULL) return NULL;

    // Выводим полученное
    printf("%s\n", cStr);
    // Освобождаем выделенную под строку область памяти
    (*env)->ReleaseStringUTFChars(env, jStr, cStr);
 
    // Получаем новый массив символов от пользователя
    char buf[128];
    scanf("%s", buf);
 
    // Преобразовываем массив символов в String
    return (*env)->NewStringUTF(env, buf);
}

Just keep in mind that Java stores strings in Modified UTF-8 encoding , while in C you work with ANSI encodings. Therefore, if you need to work with Cyrillic, you will have to take care of transcoding.

J
jcmvbkbc, 2018-04-05
@jcmvbkbc

Maybe you already read the documentation ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question