1

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[])?

1 Answer 1

1

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::strings

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.