C++ 操作结构的原始数据

标签 c++ memory

我有一个看起来像这样的简单结构:

struct Object 
{
    int x_;
    double y_;
};

我正在尝试操作对象的原始数据,这就是我所做的:

int main()
{
    Object my_object;
    unsigned char* raw_data = reinterpret_cast<unsigned char*>(&my_object);

    int x = 10;
    memcpy(raw_data, &x, sizeof(x));
    raw_data += sizeof(x);

    double y = 20.1;
    memcpy(raw_data, &y, sizeof(y));


    Object* my_object_ptr = reinterpret_cast<Object *>(raw_data);


    std::cout << *(my_object_ptr).x << std::endl;    //prints 20       (expected 10)
    std::cout << *(my_object_ptr).y << std::endl;    //prints Rubbish  (expected 20.1)
}

我期待上面的代码能工作,,,

真正的问题是什么?这可能吗?

最佳答案

您需要使用 offsetof macro .还有一些问题,最重要的是你修改了 raw_data 指针,然后将修改后的值转换回 Object* 指针,导致未定义的行为。我选择删除 raw_data 修改(替代方案是不将其强制转换,而是直接检查 my_object)。这是给你的固定代码,注释中有解释:

#include <iostream>
#include <cstring> // for memcpy
#include <cstddef> // for offsetof macro

struct Object 
{
    int x_;
    double y_;
};

int main()
{
    Object my_object;
    unsigned char* raw_data = reinterpret_cast<unsigned char*>(&my_object);

    int x = 10;
    // 1st memcpy fixed to calculate offset of x_ (even though it is probably 0)
    memcpy(raw_data + offsetof(Object, x_), &x, sizeof(x));
    //raw_data += offsetof(Object, y_); // if used, add offset of y_ instead of sizeof x

    double y = 20.1;
    // 2nd memcpy fixed to calculate offset of y_ (offset could be 4 or 8, depends on packing, sizeof int, etc)
    memcpy(raw_data + offsetof(Object, y_), &y, sizeof(y));

    // cast back to Object* pointer
    Object* my_object_ptr = reinterpret_cast<Object *>(raw_data);


    std::cout << my_object_ptr->x_ << std::endl;    //prints 10
    std::cout << my_object_ptr->y_ << std::endl;    //prints 20.1
}

关于C++ 操作结构的原始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24962307/

相关文章:

memory - 如何有效地创建一个初始化为相同值的大型项目向量?

java - 正确处理大量对象

c++ - VirtualAlloc 的困惑 - 它只适用于页面吗?

c++ - 如何在 C++ 中保留 opencv 中的最后一帧

c++ - Qt + VS2010 编译器 : How to create a simple project that would use compiled for VC staticaly linked boost?

c++ - 取消引用并通过引用返回

python - 我可以在不填充的情况下将带有位串值的字典存储在内存中吗?

c++ - 错误 :FFFFFFFFFFFFFFFF:lib(255):func(4095):reason(4095) during RSA decyption

c++ - Boost 单元测试框架 dll 导出的 std::basic_ostringstream 导致 "already defined symbol"-error

c - 释放分配的内存 : realloc() vs. free()