将 WCHAR[260] 转换为 std::string
Convert WCHAR[260] to std::string
我从Windows上的(PROCESSENTRY32)pe32.szExeFile得到了一个WCHAR[MAX_PATH]。 以下方法不起作用:
std::string s;
s = pe32.szExeFile; // compile error. cast (const char*) doesnt work either
和
std::string s;
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
s = pe32.szExeFile;
对于您的第一个示例,您可以执行以下操作:
std::wstring s(pe32.szExeFile);
第二:
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
std::wstring s(pe32.szExeFile);
由于std::wstring
有一个char*
CTOR
你对WideCharToMultiByte
的调用看起来是正确的,前提是ch
是一个足够大的缓冲区。 但是,在之后,您希望分配缓冲区(ch
)到字符串(或使用它来构造字符串),而不是 pe32.szExeFile
.
ATL有方便的转换类;你可能想使用其中的一些,例如:
std::string s( CW2A(pe32.szExeFile) );
但请注意,从 Unicode UTF-16 到 ANSI 的转换可能是有损的。如果您不想进行非有损转换,则可以从 UTF-16 转换为 UTF-8,并将 UTF-8 存储在 std::string
中。
如果您不想使用 ATL,可以使用原始 Win32 WideCharToMultiByte
周围有一些方便的免费C++包装器,可以使用 STL 字符串从 UTF-16 转换为 UTF-8。
#ifndef __STRINGCAST_H__
#define __STRINGCAST_H__
#include <vector>
#include <string>
#include <cstring>
#include <cwchar>
#include <cassert>
template<typename Td>
Td string_cast(const wchar_t* pSource, unsigned int codePage = CP_ACP);
#endif // __STRINGCAST_H__
template<>
std::string string_cast( const wchar_t* pSource, unsigned int codePage )
{
assert(pSource != 0);
size_t sourceLength = std::wcslen(pSource);
if(sourceLength > 0)
{
int length = ::WideCharToMultiByte(codePage, 0, pSource, sourceLength, NULL, 0, NULL, NULL);
if(length == 0)
return std::string();
std::vector<char> buffer( length );
::WideCharToMultiByte(codePage, 0, pSource, sourceLength, &buffer[0], length, NULL, NULL);
return std::string(buffer.begin(), buffer.end());
}
else
return std::string();
}
并按如下方式使用此模板
PWSTR CurWorkDir;
std::string CurWorkLogFile;
CurWorkDir = new WCHAR[length];
CurWorkLogFile = string_cast<std::string>(CurWorkDir);
....
delete [] CurWorkDir;
相关文章:
- 将无符号char*转换为std::istream*C++
- 将 int 数组转换为 std::vector<int*>
- 如何将这个std::字符串转换为std::基本字符串
- 哪些类型可以转换为std::any
- 如何在对<char>C++程序进行逆向工程的同时将 std::basic_string 转换为 Rust 可读值?
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 将函数参数"const char*"转换为"std::string_view"是
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 字符转换功能 std::isupper() & std::islower() C++17
- 将函数包装器转换为 std::function
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- 显式 std::exception_ptr 转换为 bool 不存在.VS2010 错误?
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- std::转换move构造函数的模板专业化的变体
- STD ::转换如何用特定值初始化函子
- 对C++字符串使用 std 转换
- 等价于元组的std::转换
- std::转换为任意容器
- std::转换顺序保证
- std::转换产生奇怪的输出