質問

I'm sure this question gets asked a lot but I just want to make sure there's not a better way to do this.

Basically, I have a const char* which points to a null-terminated C string. I have another function which expects a const wchar_t* pointing to a string with the same characters.

For the time being, I have been trying to do it like this:

    size_t newsize = strlen(myCString) + 1;
    wchar_t * wcstring = new wchar_t[newsize];
    size_t convertedChars = 0;

    mbstowcs_s(&convertedChars, wcstring, newsize, myCString, _TRUNCATE);

    delete[] wcstring;

I need to make these conversions in a lot of places since I'm dealing with 3rd party libraries which expect one or the other. Is this the recommended way to go about this?

役に立ちましたか?

解決

What you're doing is pretty much the recommended way of doing it, assuming that your data is all ASCII. If you have non-ASCII data in there, you need to know what its encoding is: UTF-8, Windows-1252, any of the ISO 8859 variants, SHIFT-JIS, etc. Each one needs to be converted in a different way.

The only thing I would change would be to use mbstowcs instead of mbstowcs_s. mbstowcs_s is only available on Windows, while mbstowcs is a standard C99 function which is portable. Of course, if you'd like to avoid the CRT deprecation warnings with the Microsoft compiler without completely turning them off, it's perfectly fine to use a macro of #if test to use mbstowcs on non-Windows systems and mbstowcs_s on Windows systems.

You can also use mbstowcs to get the length of the converted string by first passing in NULL for the destination. That way, you can avoid truncation no matter how long the input string is; however, it does involve converting the string twice.

For non-ASCII conversions, I recommend using libiconv.

他のヒント

You haven't said what encodings are involved. If you have non-multibyte strings, you can just use this:

std::string a("hello");
std::wstring b(s.begin(), s.end());

const wchar_t *wcString= b.c_str();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top