C++ 如何将内存读入wstring?

C++ 如何将内存读入wstring?,c++,wstring,C++,Wstring,我已经尝试过使用wchar\u t和for循环来读取wchar-by-wchar的内存,并且成功了。 工作代码: int cl = 20; std::wstring wstr; wchar_t L; for (int i = 0; i < cl; i++) { ReadProcessMemory(ProcHandle, (unsigned char*)Address, &L, 2, NULL); Address += 2; wstr.push_back(L); } std::wco

我已经尝试过使用wchar\u t和for循环来读取wchar-by-wchar的内存,并且成功了。 工作代码:

int cl = 20;
std::wstring wstr;
wchar_t L;
for (int i = 0; i < cl; i++) {
ReadProcessMemory(ProcHandle, (unsigned char*)Address, &L, 2, NULL);
Address += 2;
wstr.push_back(L);
}
std::wcout << wstr << std::endl;
现在,当我尝试使用std::wstring并直接读取它时,无论出于何种原因,它都失败了

int cl = 20;
std::wstring L;
L.resize(cl); // could use reserve?
ReadProcessMemory(ProcHandle, (unsigned char*)Address, &L, cl*2, NULL);
std::wcout << L << std::endl;

我想我应该使用cl*2作为大小,因为wchar\u t有2个字符大小

我希望它将wstring打印到wcout,但它会出现类似于读取失败序列的错误

注意:我不能使用wchat_t[20],因为我以后希望cl是动态的

编辑:忘了说我在std c++17上,std::vector更适合您的情况


&L是字符串对象的地址,而不是字符串缓冲区。您想使用&L[0],第一个wchar的地址

因为wchar\u t有2个字符大小。-你真的确定你确实得到了保证吗?请在问题中包含准确的错误信息,而不仅仅是类似的信息//可以使用保留?不。保留实际上不会增加字符串的大小。即使您知道分配的内存对它有好处,您仍然会在字符串的边界之外写入内容。例如,如果复制L,则可能无法正确复制数据。据它所知,大小仍然为0,因此它将尝试复制0个字符。更好的是,L.data.data==better.Agree。但是我们不知道OPL使用了什么C++。C++是什么标准?因为即使没有c++11,它也应该可以工作。@unlut well,yes和no。可变。数据仅为c++17,这是OP所需要的。