我想使用malloc创建一个相当于结构体的内存块,如下面的代码所示,但我收到警告“C6378 'pMyStructByMalloc' could be '0'”,并且似乎无法使其工作。
struct MyStruct
{
int a = 1;
std::string s = "test";
int b = 2;
};
MyStruct* pMyStruct = new MyStruct();
int a = 1;
int b = 2;
std::string s = "test";
int memorySize = sizeof(int) + sizeof(std::string) + sizeof(int);
char* pMyStructByMalloc = (char*)malloc(memorySize);
memcpy(pMyStructByMalloc, &a, sizeof(int)); // C6378 'pMyStructByMalloc' could be '0'
memcpy((pMyStructByMalloc + sizeof(int)), &s, sizeof(std::string));
memcpy((pMyStructByMalloc + sizeof(int) + +sizeof(std::string)), &b, sizeof(int));
字符串
有没有办法成功做到这一点?
使用malloc创建一个相当于struct的内存块。
好的,那么如果结构有固定的长度并且
struct MyStruct
{
int a = 1;
float s = 10.0f;
int b = 2;
};
型
我试着看看我是否可以“伪造”相同类型的内存,并在不使用任何MyStruct的情况下将内存块发送给某个低级函数。(假设我没有引用MyStruct代码,但只知道数据结构)
Potscript 2
API如下所示
TheAPI(int32 bufferSize, void * data);
型
我通常这样做,
TheAPI(sizeof(MyStruct), pMyStruct);
型
但这次我想动态地
TheAPI(memorySize , pMyStructByMalloc)
型
这样,我可以尝试不同形式的内存。(不同类型的固定大小的结构)
2条答案
按热度按时间wgxvkvu91#
要复制一个结构体,提供一个复制构造函数。这将确保你的std::string也被正确复制,并将开始其生存期。
字符串
xmjla07d2#
如果你有一个缓冲区,你想让它代表一个对象,你应该使用placement new操作符或c20 construct_at在一个特定的位置调用构造函数/复制构造函数,这保证了对象的生存期开始。(并防止删除未构造的字符串),你也需要调用析构函数(或c20 destroy_at)当你不再使用对象释放任何资源。
字符串
注意
std::vector
有一个对齐要求,要对齐到任何标准类型,所以它可以用来包含MyStruct
,但是如果你是从其他地方(比如malloc)获得这个内存,你需要确保内存是正确对齐的,否则placement new
操作符将向前推动指针来补偿对齐要求。