1
以下是將託管字符串轉換爲本地字符指針的方法,輸入字符串爲「€」時將返回錯誤代碼42 ASCII 128D):在C++ CLI中輸入字符串爲「€」(ASCII 128d)時,wcstombs_s失敗
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字節> = 128)? (見this)
你在託管代碼。你爲什麼使用wcstombs_s而不是System :: Text :: Encoding? – Medinoc 2014-12-24 13:07:12
我需要固定指針並讓本地dll訪問它 – 2014-12-24 16:41:54
然後完成這個操作,或者使用Encoding的基於指針的方法:http://msdn.microsoft.com/en-us/library/6s1x2atd%28v=vs.80 %29.aspx – Medinoc 2014-12-24 20:13:43