0

How to convert a jstring to a C++ std::string?

CppMethod(const std::sting& cpp_str) {
    std::cout << "The string on CPP side is" << cpp_str << std::endl;
}


#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL Java_com_something_something_someClass_someMethod(JNIEnv * env,
                                          jobject /*this_obj*/, jstring jstring_str)
{
    std::string cpp_str;
    // How to copy jstring_str into cpp_str??
    CppMethod(cpp_str)
}

#ifdef __cplusplus
}
#endif
}

Basically, How can I get the content of jstring_str into cpp_str ?

AdeleGoldberg
  • 1,289
  • 3
  • 12
  • 28
  • How exactly is your Java and C++ code interoperating? Kinda light on the details here. – StoryTeller - Unslander Monica Mar 04 '20 at 13:06
  • I would like to know more too, your use case, and how you bridge them, the code above is clueless. – Angus Mar 04 '20 at 13:09
  • Sorry. I corrected my question with more details. I have already converted the Java String into jstring as I understand that I need to get it over the JNI bridge. Now how can I convert the `jstring` into a `std::string`? – AdeleGoldberg Mar 04 '20 at 13:13
  • The JNI bridge from java to C++ is working alright. I just need to know how to get the jstring to the C++ side. I dont need to understand JNI details as a part of the answer. I am already dealing with some JNI which gives me a fair understanding of it. – AdeleGoldberg Mar 04 '20 at 13:14
  • 1
    https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo009 - once you have converted `jstring` to `const char *c_str` in `JNI` code, you can do `std::string str(c_str);` – Oo.oO Mar 04 '20 at 13:29
  • I think it does. Thanks a lot – AdeleGoldberg Mar 04 '20 at 13:41

0 Answers0