c++ 使用malloc创建相当于struct的内存块

relj7zay  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(88)

我想使用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)


这样,我可以尝试不同形式的内存。(不同类型的固定大小的结构)

wgxvkvu9

wgxvkvu91#

要复制一个结构体,提供一个复制构造函数。这将确保你的std::string也被正确复制,并将开始其生存期。

#include <cassert>
#include <string>
#include <iostream>

struct MyStruct
{
    MyStruct() = default;
    ~MyStruct() = default;

    MyStruct(const MyStruct& rhs) :
        a{rhs.a},
        s{rhs.s},
        b{rhs.b}
    {
        std::cout << "Copy constructor";
    }

    // todo copy assignment, move constructor & move assignment
    
    int a = 1;
    std::string s = "test";
    int b = 2;
};

int main()
{
    MyStruct my_struct;
    auto copy_of_my_struct{my_struct};

    assert(copy_of_my_struct.a == 1);
    assert(copy_of_my_struct.s == std::string{"test"});
    assert(copy_of_my_struct.b == 2);
}

字符串

xmjla07d

xmjla07d2#

如果你有一个缓冲区,你想让它代表一个对象,你应该使用placement new操作符或c20 construct_at在一个特定的位置调用构造函数/复制构造函数,这保证了对象的生存期开始。(并防止删除未构造的字符串),你也需要调用析构函数(或c20 destroy_at)当你不再使用对象释放任何资源。

#include <string>
#include <vector>

struct MyStruct
{
    int a = 1;
    std::string s = "test";
    int b = 2;
};

int main()
{
    std::vector<char> buffer = std::vector<char>(sizeof(MyStruct));
    MyStruct object1 = MyStruct();
    MyStruct* object2 = new (&buffer[0]) MyStruct{object1};
    object2->~MyStruct(); // delete object to end its lifetime
    return 0;
}

字符串
注意std::vector有一个对齐要求,要对齐到任何标准类型,所以它可以用来包含MyStruct,但是如果你是从其他地方(比如malloc)获得这个内存,你需要确保内存是正确对齐的,否则placement new操作符将向前推动指针来补偿对齐要求。

相关问题