在char数组

时间:2018-02-25 13:14:36

标签: char byte c++builder

我正在尝试了解有关C ++内存管理和类型转换的更多信息。如何在char数组中存储和检索std :: wstring *?关于阅读什么的代码或建议将不胜感激。

这是我到目前为止所尝试的内容。我对" Works"的定义是GUI控件中出现正确的字符串。 "不起作用"意味着它编译并运行但在GUI控件中给我一个空白。

我真的很好奇为什么" Wrapper 2"有效,但不是" Wrapper 1"。

整数示例(Works):

int* lInt(new int);
*lInt = 1500000;
char lBuffer[sizeof(void*)];
memcpy(lBuffer, lInt, sizeof(void*));
int* lInt2 = (int*)lBuffer;
Memo->Lines->Append(IntToStr(*lInt2)); //C++Builder GUI control 
delete lInt;

std :: wstring示例(不起作用):

std::wstring* lMyString = new std::wstring();
*lMyString = L"My Name";
char lBuffer[sizeof(void*)];
memcpy(lBuffer, lMyString, sizeof(void*));
std::wstring* lMyString2 = (std::wstring*)lBuffer;
Memo->Lines->Append(lMyString2->c_str());  //C++Builder GUI control 
delete lMyString;

包装1(不起作用):

struct MyString
{
    std::wstring Text;
};
MyString* lMyString = new MyString();
lMyString->Text = L"My Name";
char lBuffer[sizeof(void*)];
memcpy(lBuffer, lMyString, sizeof(void*));
MyString* lMyString2 = (MyString*)lBuffer;
Memo->Lines->Append(lMyString2->Text.c_str());  //C++Builder GUI control 
delete lMyString;

Wrapper 2(Works):

struct MyString
{
    MyString(): Text(new std::wstring()){};
    ~MyString() {delete Text;};
    std::wstring* Text;
};
MyString* lMyString = new MyString();
*lMyString->Text = L"My Name";
char lBuffer[sizeof(void*)];
memcpy(lBuffer, lMyString, sizeof(void*));
MyString* lMyString2 = (MyString*)lBuffer;
Memo->Lines->Append(lMyString2->Text->c_str());  //C++Builder GUI control 
delete lMyString;

1 个答案:

答案 0 :(得分:-1)

  

如何在char数组中存储和检索std :: wstring *?

更好的方法是将其存储在void*

std::wstring ws;
void *addr = &ws;
// ...
std::wstring retreived = *static_cast<std::wstring*>(addr);
  

***** std :: wstring示例(不起作用)*****

std::wstring* lMyString = new std::wstring();
// ...
char lBuffer[sizeof(void*)];
memcpy(lBuffer, lMyString, sizeof(void*));
std::wstring* lMyString2 = (std::wstring*)lBuffer;
// ...
以这种方式使用的

memcpy实际上复制了存储的std :: wstring的字节。

void* memcpy( void* dest, const void* src, std::size_t count );

lMyString是指向从内存std::wstring指向的已分配memcpysrc个字节的指针。你真正想要做的是复制指针本身,所以你需要获取指针的地址:

memcpy(lBuffer, &lMyString, sizeof(void*));
 std::wstring* lMyString2 = (std::wstring*)lBuffer;

这也是错误的。您正在转换char[]中第一个字符的地址,而不是之前存储在char数组中的实际字节。你应该memcpy回来:

std::wstring* lMyString2 = nullptr;
std::memcpy(&lMyString2, lBuffer, sizeof(void*));

正如我所说,请改用void*