[英]C++ - How do you convert from String to TCHAR*?
這是我的代碼:
string str = "Hello!";
TCHAR* tch = new TCHAR[str.length() + 1];
mbstowcs_s(NULL, tch, _tcslen(tch), str.c_str(), str.length());
// Use tch for other stuff...
delete [] tch; // Gives debug heap corruption assertion
由於某種原因,我在此代碼中得到了堆損壞斷言。 我竭盡全力試圖找出可能出問題的地方。 對於字符串和tchar之間的異同,我找不到任何好的文檔,這可以幫助我自己解決這個問題。
_tcslen(tch)
給出錯誤的結果,因為此時tch
尚未初始化。 我假設您應該在那里傳遞str.length() + 1
(緩沖區的大小)。
您試圖在初始化其內容之前在tch上使用_tcslen
。
從事物的外觀上,您想要更接近的東西:
mbstwcs_s(NULL, tch, str.length(), str.c_str(), str.length());
如果您詢問有關C ++的信息,請使用ATL字符串轉換類代替手動的內存管理和WinApi調用:
string str = "Hello!";
CA2T tstr(str.c_str());
SomeFunctionT(tstr);
您也可以內聯使用這些類:
string str = "Hello!";
SomeFunctionT(CA2T(str.c_str()));
注意:您需要包括atlbase.h。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.