lundi 26 juillet 2010

C++/CLI String^ to std::string and vice-versa

I propose you 2 functions for converting std::string to/from String^ in C++/CLI

    String^ UTF8ToString( const char *s ) {
        int len = strlen(s);
        cli::array^ a = gcnew cli::array(len);
        int i = len;
        while (i-- > 0) {
            a[i] = s[i];
        }
        return System::Text::Encoding::UTF8->GetString(a);
    };

    std::string StringToUTF8( String ^ s) {
        System::Text::UTF8Encoding^ utf8 = gcnew System::Text::UTF8Encoding;
        array^encodedBytes = utf8->GetBytes(s);
        std::string os="";
        for (int i=0;iLength;i++) {
            os+=encodedBytes[i];
        }
        return os;
    }


Useful to work with other libs working in UTF-8 like sqlite...

Aucun commentaire:

Enregistrer un commentaire