11

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.

4
  • 2
    Note that std::basic_string<wchar_t> is typedef'ed to std::wstring. Commented Aug 8, 2011 at 23:24
  • 1
    possible duplicate of How do I convert jstring to wchar_t * Commented Aug 8, 2011 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. Commented Aug 8, 2011 at 23:45
  • possible duplicate of stackoverflow.com/questions/870414/… Commented Aug 8, 2011 at 23:53

1 Answer 1

14

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

2 Comments

That expects a const char*. What if I need to convert from std::string?
@Igor Use the std::string member .c_str().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.