10

I'm using a basic_string<wchar_t> type and need to convert it into a jstring to pass through a JNI layer. I'm wondering what the best way to do that is. I have a function that can give me a std::string from my basic_string<wchar_t> type, so an answer to that would also be cool.

Cheers.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
sparkFinder
  • 3,336
  • 10
  • 42
  • 57
  • 2
    Note that `std::basic_string` is typedef'ed to `std::wstring`. – Kerrek SB Aug 08 '11 at 23:24
  • 1
    possible duplicate of [How do I convert jstring to wchar_t *](http://stackoverflow.com/questions/68042/how-do-i-convert-jstring-to-wchar-t) –  Aug 08 '11 at 23:33
  • Am trying to do the reverse of that, and am trying to see if I can avoid using a char* anywhere in there. – sparkFinder Aug 08 '11 at 23:45
  • possible duplicate of http://stackoverflow.com/questions/870414/passing-double-byte-wchar-strings-from-c-to-java-via-jni –  Aug 08 '11 at 23:53

1 Answers1

12

You'll need to convert the std::basic_string into UTF-8. Look into what your wstring -> string conversion does.

Sun has a JNI tutorial that shows how to convert a char* into a jstring (using some UTF conversion routines). You could use your wstring->string, then pass in string.c_str() to the NewStringUTF function:

Untested Code:

JNIEXPORT jstring JNICALL StringTest(JNIEnv *env) {
    const char* test = "something";
    return env->NewStringUTF(test);
}
zwcloud
  • 4,546
  • 3
  • 40
  • 69
Tim Finer
  • 565
  • 6
  • 13