简体   繁体   中英

JNI Pass a String from java to c++ and then pass c++ string to string Array

I declared native method in java.

static
{
    // Replace "Myfile" with the name of your Native File
    System.loadLibrary("JohnnyX");
}

// Declare your native methods here
public static native String string(StringBuffer sb);

and pass a string buffer to it.

System.out.println(string(sb));

and in my JohnnyX.cpp, I am using following method to convert java string into c++ string.

std::string jstring2string(JNIEnv *env, jstring jStr) 
{
    if (!jStr)
        return "";

    const jclass stringClass = env->GetObjectClass(jStr);
    const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
    const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes,
                                                                       env->NewStringUTF("UTF-8"));

    size_t length = (size_t) env->GetArrayLength(stringJbytes);
    jbyte *pBytes = env->GetByteArrayElements(stringJbytes, NULL);

    std::string ret = std::string((char *) pBytes, length);
    env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_ABORT);

    env->DeleteLocalRef(stringJbytes);
    env->DeleteLocalRef(stringClass);
    return ret;
}

extern "C" JNIEXPORT jstring JNICALL Java_com_example_rsolver_Solver_string(JNIEnv *env, jobject object,jstring string) {
    // Converting Java String into C++ String and calling a "solution" method and passing c++ string
    return solution(jstring2string(env,string));
}

My solution Method is :

string solution (string argv[]) {
    // this will return a string
}

My problem is that How can i pass c++ string to string array in solution(string argv[])?

One simple solution is a temporary string object

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_rsolver_Solver_string(JNIEnv *env, jobject object,jstring string) {
    // Converting Java String into C++ String and 
    // calling a "solution" method and passing c++ string
    std::string tmp{jstring2string(env,string)};
    return solution(&tmp);
}

This gives an array of 1 element to solution . But solution() does not know how many elements this array has, so you must add the array size too

std::string solution (int size, std::string argv[]) {
    // this will return a string
}

// ...
std::string tmp{jstring2string(env, string)};
return solution(1, &tmp);

Better yet, skip raw arrays, and pass a std::vector of std::string s

std::string solution (const std::vector<std::string> &argv) {
    // this will return a string
}

// ...
std::vector<std::string> tmp = { jstring2string(env, string) };
return solution(tmp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM