You need to enable JavaScript to run this app. 使用boost::interprocess共享内存时如何读取结构体指针成员的值
优惠活动
大模型
产品
解决方案
定价
更多

使用boost::interprocess共享内存时如何读取结构体指针成员的值

问题原因与解决方案

核心报错原因

  • 第一阶段错误:最开始用new int分配的内存属于当前进程的私有虚拟地址空间,这块内存不在共享内存段里,其他进程完全无法访问,所以receiver拿到指针直接访问必然触发访问冲突。
  • 第二阶段修改后仍报错的核心原因:不同进程映射同一块共享内存的虚拟基地址可能不同,你存的是sender进程中共享内存段里的绝对虚拟地址,到了receiver进程中这个地址对应的不是共享内存的位置,所以仍然访问非法。

修复步骤

1. 修改结构体定义

把结构体里的原生指针全部替换为boost::interprocess::offset_ptr,这个指针会自动存储相对于共享内存段基址的偏移量,跨进程可以自动适配不同的映射基址。sender和receiver两边都要使用完全相同的结构体定义:

#include <boost/interprocess/offset_ptr.hpp>

struct test {
    boost::interprocess::offset_ptr<int> pInt;
    boost::interprocess::offset_ptr<float> pFloat;
};

2. 完善sender代码

你修改后的分配逻辑是对的,补充赋值操作即可,offset_ptr支持直接接收共享内存分配的原生指针赋值:

using namespace boost::interprocess;

int main(int argc, char* argv[])
{
    shared_memory_object::remove("my_shm");
    managed_shared_memory managed_shm(open_or_create, "my_shm", 1024);

    allocator<int, managed_shared_memory::segment_manager> int_alloc(managed_shm.get_segment_manager());
    test* i = managed_shm.construct<test>("my_solve")();
    // 分配共享内存的int
    auto allocated_int = int_alloc.allocate(1);
    // 赋值目标数值
    *allocated_int = 2;
    // 赋值给offset_ptr,自动计算跨进程兼容的偏移量
    i->pInt = allocated_int;
    
    return 0;
}

3. receiver代码调整

receiver不需要修改核心逻辑,只要保证使用的结构体是带offset_ptr的版本即可,直接访问*ans->pInt就能正确拿到值,额外补充共享内存资源释放逻辑避免内存泄漏:

int main(int argc, char* argv[])
{
    using namespace boost::interprocess;
    // 建议用open_only避免sender没启动时创建空共享内存,导致找不到对象
    managed_shared_memory managed_shm(open_only, "my_shm", 1024);
    test* ans = managed_shm.find<test>("my_solve").first;
    if (ans)
    {
        std::cout << "Read from shared memory\n";
        std::cout << "print address ans: " << ans<< std::endl;
        std::cout << "print address ans->pInt: " << ans->pInt.get() << std::endl;
        std::cout << "print value ans->pInt: " << *(ans->pInt) << std::endl;

        // 用完释放分配的int内存,避免共享内存泄漏
        allocator<int, managed_shared_memory::segment_manager> int_alloc(managed_shm.get_segment_manager());
        int_alloc.deallocate(ans->pInt.get(), 1);
    }
    else
        std::cout << "my_solve not found" << '\n';

    managed_shm.destroy<test>("my_solve");
    shared_memory_object::remove("my_shm");

    return 0;
}

额外注意事项

  • 所有存到共享内存里的指针类型都必须用offset_ptr,不能用原生指针
  • 共享内存里分配的动态内存,必须用对应的共享内存分配器释放,不能用delete
  • receiver打开共享内存建议用open_only参数,避免sender未正常创建共享内存时,receiver自行创建空段导致找不到对象的问题

内容的提问来源于stack exchange,提问作者Hien Pham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 23:42:03