2011-06-16 36 views
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

+0

你在託管代碼。你爲什麼使用wcstombs_s而不是System :: Text :: Encoding? – Medinoc 2014-12-24 13:07:12

+0

我需要固定指針並讓本地dll訪問它 – 2014-12-24 16:41:54

+0

然後完成這個操作,或者使用Encoding的基於指針的方法:http://msdn.microsoft.com/en-us/library/6s1x2atd%28v=vs.80 %29.aspx – Medinoc 2014-12-24 20:13:43

回答

0

從MSDN文檔有關wcstombs_s

如果wcstombs_s遇到寬字符不能轉換爲多字節字符,它以* pReturnValue會將0,將目標緩衝區爲空字符串,將errno設置爲EILSEQ,並返回EILSEQ。

EILSEQ是錯誤代碼42

要轉換Unicode字符串爲char *數組,我建議得到Unicode字符串的二進制數組,並使用Base64編碼,它和編碼的結果存儲在一個char *數組。