2009-09-16 59 views
0

我是新來C++,所以這可能是一個noobish問題;我有以下功能:BSTR和SysAllockStringByteLen()在C + +

#define SAFECOPYLEN(dest, src, maxlen)        \ 
{                 \ 
    strncpy_s(dest, maxlen, src, _TRUNCATE);       \ 
    dest[maxlen-1] = '\0';           \ 
} 

short _stdcall CreateCustomer(char* AccountNo) 
{ 
    char tmpAccountNumber[9]; 
    SAFECOPYLEN(tmpAccountNumber, AccountNo, 9); 
    BSTR strAccountNumber = SysAllocStringByteLen(tmpAccountNUmber, 9); 

    //Continue with other stuff here. 
} 

當我通過這段代碼調試,我通過在賬號「A101683」的例子。當它執行SysAllocStringByteLen()部分時,帳號成爲中文符號的組合...

任何人都可以對此有所瞭解?

+0

什麼是SAFECOPYLEN? – Naveen 2009-09-16 08:11:16

+0

用SAFECOPYLEN定義更新。 – 2009-09-16 08:26:29

回答

4

SysAllocStringByteLen是用於創建包含二進制數據的BSTR而不是實際的字符串 - 不執行ANSI到Unicode的轉換。這就解釋了爲什麼調試器顯示字符串包含明顯的中文符號,它試圖將複製到BSTR中的ANSI字符串解釋爲unicode。您應該使用SysAllocString而不是 - 這將正確地將字符串轉換爲unicode 您必須將它傳遞給unicode字符串。如果你正在處理實際的文本,這是你應該使用的功能。

+2

一般想法是正確的,但是SysAllocString()不會執行ANSI到Unicode的轉換。你需要自己做:http://stackoverflow.com/questions/606075/how-to-convert-char-to-bstr/606122#606122 – sharptooth 2009-09-16 08:20:31

+0

是的,我正在處理實際文本,而不是二進制數據。你的意思是我應該在這種情況下使用SysAllocString()而不是SysAllocStringByteLen()嗎? – 2009-09-16 08:41:51

+1

是的,要得到一個BSTR,您需要調用SysAllocString()或SysAllocStringLen(),並在鏈接答案中執行ANSI到Unicode的轉換。 – sharptooth 2009-09-16 08:49:44

0

首先,包含SAFECOPYLEN的行存在問題。這是'''',並不清楚它應該做什麼。

第二個問題是您沒有在此代碼中的任何地方使用AccountNo。 tmpAccountNumber在堆棧中,並且可以包含任何內容。

+0

我只重新輸入了與我的問題相關的部分功能。我犯了一個錯誤,現在更新了。 – 2009-09-16 08:22:43

0

BSTR是雙字節字符數組,因此您不能僅將char *數組複製到其中。而不是通過它"A12123"嘗試L"A12323"

short _stdcall CreateCustomer(wchar_t* AccountNo) 
{ 
wchar_t tmpAccountNumber[9]; 
wcscpy(tmpAccountNumber[9], AccountNo); 
BSTR strAccountNumber = SysAllocStringByteLen(tmpAccountNUmber, 9); 

//Continue with other stuff here. 
}