有人会碰巧知道如何将类型转换LPTSTR
为char *
C++吗?
取决于它是否是Unicode,它出现.如果不是Unicode,LPTSTR是char*,如果不是,则为w_char*.
在这里讨论得更好(接受的答案值得一读)
这有很多方法可以做到这一点.MFC或ATL的CString,ATL宏或Win32 API.
LPTSTR szString = _T("Testing"); char* pBuffer;
您可以使用ATL宏进行转换:
USES_CONVERSION; pBuffer = T2A(szString);
CString的:
CStringA cstrText(szString);
或在Win32 API WideCharToMultiByte
如果UNICODE
被定义.
如果编译器字符设置设置为Unicode字符集,则LPTSTR将被解释为wchar_t*.在这种情况下,需要Unicode到多字节字符转换.
(在Visual Studio中,设置位于项目属性\配置属性\常规\字符集)
下面的示例代码应该提供一个想法:
#include/* string consisting of several Asian characters */ LPTSTR wcsString = L"\u9580\u961c\u9640\u963f\u963b\u9644"; //LPTSTR wcsString = L"OnlyAsciiCharacters"; char* encode(const wchar_t* wstr, unsigned int codePage) { int sizeNeeded = WideCharToMultiByte(codePage, 0, wstr, -1, NULL, 0, NULL, NULL); char* encodedStr = new char[sizeNeeded]; WideCharToMultiByte(codePage, 0, wstr, -1, encodedStr, sizeNeeded, NULL, NULL); return encodedStr; } wchar_t* decode(const char* encodedStr, unsigned int codePage) { int sizeNeeded = MultiByteToWideChar(codePage, 0, encodedStr, -1, NULL, 0); wchar_t* decodedStr = new wchar_t[sizeNeeded ]; MultiByteToWideChar(codePage, 0, encodedStr, -1, decodedStr, sizeNeeded ); return decodedStr; } int main(int argc, char* argv[]) { char* str = encode(wcsString, CP_UTF8); //UTF-8 encoding wchar_t* wstr = decode(str, CP_UTF8); //If the wcsString is UTF-8 encodable, then this comparison will result to true. //(As i remember some of the Chinese dialects cannot be UTF-8 encoded bool ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; delete str; delete wstr; str = encode(wcsString, 20127); //US-ASCII (7-bit) encoding wstr = decode(str, 20127); //If there were non-ascii characters existing on wcsString, //we cannot return back, since some of the data is lost ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; delete str; delete wstr; }
另一方面,如果编译器字符设置设置为多字节,则LPTSTR将被解释为char*.
在这种情况下:
LPTSTR x = "test"; char* y; y = x;
另见:
关于wchar_t转换的另一个讨论:如何正确使用WideCharToMultiByte
MSDN文章:http://msdn.microsoft.com/en-us/library/dd374130(v = vs.85).aspx
有效代码页标识符:http:// msdn.microsoft.com/en-us/library/dd317756(v=vs.85).aspx