wcstombs_s fails when input string is "€" (ASCII 128d) in C++\CLI
Here is the method to convert from managed string to native char pointer, it'll return error code 42 when the input string is "€" (ASCII 128d):
void StringUtility::ManagedToNative(String^ source, char* pTarget, Int32 targetLength)
{
if(pTarget == NULL)
throw gcnew System::ArgumentNullException("The source pointer cannot be empty.");
if(targetLength <= 0)
throw gcnew System::ArgumentOutOfRangeException("The target length has to be larger than 0.");
memset(pTarget, 0, targetLength);
if(String::IsNullOrEmpty(source))
{
pTarget[0] = '\0';
return;
}
// Conversion to char* :
size_t convertedChars = 0;
size_t sizeInBytes = targetLength;
size_t count = (source->Length > targetLength) ? _TRUNCATE : targetLength;
errno_t err = 0;
{
/* minimize the scope of pined object */
pin_ptr<const wchar_t> wch = PtrToStringChars(source);
err = wcstombs_s(&convertedChars, pTarget, sizeInBytes, wch, count);
}
// if truncate did happen and it's intended, return as successful.
if( count == _TRUNCAT开发者_开发问答E && err == STRUNCATE )
return;
if (err != 0)
throw gcnew System::InvalidOperationException("convert from String^ to char* failed");
}
Is it just because I can't convert any string (with bytes >= 128) using wcstombs_s? (see this)
From MSDN doc about wcstombs_s:
If wcstombs_s encounters a wide character it cannot convert to a multibyte character, it puts 0 in *pReturnValue, sets the destination buffer to an empty string, sets errno to EILSEQ, and returns EILSEQ.
EILSEQ is error code 42.
To convert Unicode string to char* array, I'd suggest get the binary array of the Unicode string and encode it using Base64 and store the encoded result in a char* array.
精彩评论