以下是从托管字符串转换为本机字符指针的方法,当输入字符串为“€”(ASCII 128d)时,它将返回错误代码42:
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 == _TRUNCATE && err == STRUNCATE )
return;
if (err != 0)
throw gcnew System::InvalidOperationException("convert from String^ to char* failed");
}
是不是因为我无法使用wcstombs_s转换任何字符串(字节&gt; = 128)? (见this)
答案 0 :(得分:0)
来自MSDN doc wcstombs_s:
如果wcstombs_s遇到宽字符,则无法转换为多字节字符,它将0放在* pReturnValue中,将目标缓冲区设置为空字符串,将errno设置为EILSEQ,然后返回EILSEQ。
EILSEQ是错误代码42。
要将Unicode字符串转换为char *数组,我建议获取Unicode字符串的二进制数组并使用Base64对其进行编码,并将编码结果存储在char *数组中。