Jstring conversion

edited August 2014 in Native
What is the best way to convert a string to a Jstring and from a Jstring to a string?

Comments

  • Hi kblanch09.

    I assume, that with string you mean a std::string, correct?

    It's actually pretty easy:
    [code2=cpp]ExitGames::Common::JString jstr = L"string"; // initial JString instance construction from a const wchar_t*
    std::string str = jstr.UTF8Representation().cstr(); // construction of a std::string instance with the content of that JString instance
    jstr = str.c_str(); // assignment of the content of the std::string instance back to the JString instance
    printf("%s %ls\n", str.c_str(), jstr.cstr()); // output of both through printf
    std::cout << str << " " << jstr.UTF8Representation() << std::endl; // and through std::cout[/code2]
  • Thanks!!!
  • esdebonesdebon
    edited November 2020
    I need convert a variable _jstring to ExitGames::Common::JString

    In the example is only a constan

    I need convert:
    jstring myString = 'La cadena';

    to ExitGames::Common::JString jstr

    but _jstring have not the method UTF8Representation()

    Any clue?
  • Hi @esdebon.
    but _jstring have not the method UTF8Representation()
    That is, because UTF8Representation() is a function of ExitGames::Common::JString. The original question was how to convert FROM a JString to some other string format (in this case std::string).
    You now ask how to convert from some other string format TO a JString.

    A JString can be initialized with either an array of UTF8 encoded char or with an array of wchar_t that is encoded in Unicode according to the size of wchar_t on the platform that you are compiling for, hence UTF16 on Windows and UTF32 on Unixes (FYI: iOS, Android and OS X are all Unixes).

    Hence you need to read the documentation of the string class that you are converting from to find out how to get a char* or a wchar_t* representation of it.

    Your other string class is called jstring (with a small 'j' and a small 's', unlike Photons JString class that is written with a capital 'J' and a capital 'S').
    The only class with such a name that I have heard of is the JNI jstring class.
    Therefor I assume that you are talking about Android. Is that correct?

    JNI offers a GetStringUTFChars() function that takes a jstring instance and returns a UTF8 encoded char array (see https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html).

    That char* can then be passed to the JString constructor.
  • You are the best!!! GetStringUTFChars() works perfectly Thank you very much!!!
Sign In or Register to comment.