无法将 CString 转换为 BYTE 数组
我需要将 CString 转换为 BYTE 数组。我不知道为什么,但我在互联网上找到的所有内容都不起作用:( 例如,我一直在
CString str = _T("string");
尝试这样 1)
BYTE *pbBuffer = (BYTE*)(LPCTSTR)str;
2)
BYTE *pbBuffer = new BYTE[str.GetLength()+1];
memcpy(pbBuffer, (VOID*)(LPCTSTR)StrRegID, str.GetLength());
3)
BYTE *pbBuffer = (BYTE*)str.GetString();
并且总是 pbBuffer 只包含 str 的第一个字母
DWORD dwBufferLen = strlen((char *)pbBuffer)+1;
是 2
但如果我使用 const 字符串:
BYTE *pbBuffer = (BYTE*)"string";
pbBuffer 包含整个
字符串是我的错吗?
I need to convert CString to BYTE array. I don't know why, but everything that I found in internet does not work :(
For example, I have
CString str = _T("string");
I've been trying so
1)
BYTE *pbBuffer = (BYTE*)(LPCTSTR)str;
2)
BYTE *pbBuffer = new BYTE[str.GetLength()+1];
memcpy(pbBuffer, (VOID*)(LPCTSTR)StrRegID, str.GetLength());
3)
BYTE *pbBuffer = (BYTE*)str.GetString();
And always pbBuffer contains just first letter of str
DWORD dwBufferLen = strlen((char *)pbBuffer)+1;
is 2
But if I use const string:
BYTE *pbBuffer = (BYTE*)"string";
pbBuffer contains whole string
Where is my mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 CString 是 Unicode(每个字符两个字节),并且您尝试将其解释为 ANSI(每个字符一个字节)。这会导致您意想不到的结果。
您需要转换数据,而不是将底层缓冲区转换为
char*
。为此,请使用 WideCharToMultiByte() 。Your CString is Unicode (two bytes per character) and you try to interpret it as ANSI (one byte per character). This leads to results you don't expect.
Instead of casting the underlying buffer into
char*
you need to convert the data. Use WideCharToMultiByte() for that.您可能正在使用 unicode 进行编译。这意味着您的 CString 包含 wchar_t 而不是 char。将 wchar_t 指针转换为 char 指针会导致您将第一个 wchar_t 的第二个字节解释为字符串终止符(因为对于最常见的字符,by 为 0)
当使用 Visual Studio 时,您应该始终使用 _T() 来声明字符串文字和 TCHAR 作为您的字符类型。在你的情况下:
你得到了缓冲区,但每个其他字节很可能为零。
如果需要 ANSI 字符串,请使用 CStringA。 (但是在初始化时跳过_T())
You are probably compiling with unicode. This means that your CString contains wchar_t instead of char. Converting a wchar_t pointer to a char pointer causes you to interpret the second byte of the first wchar_t as a string terminator (since that by is 0 for the most common characters)
When using visual studio you should always use _T() to declare string literals and TCHAR as your character type. In your case:
You get the buffer, but every other byte is most probably zero.
Use a CStringA if you need an ANSI string. (But then skip the _T() when initializing it)