【问题标题】:How to get value of pointer member in struct with boost::interprocess如何使用 boost::interprocess 在结构中获取指针成员的值
【发布时间】:2021-10-11 03:09:50
【问题描述】:

我是 boost 库的新手。我正在尝试使用 boost::interprocess 在共享内存中分配一个非常简单的数据结构。我的结构如下所示:

struct test {
    int* pInt;
    float* pFloat;
};

这里是 sender.cpp:

using namespace boost::interprocess;

int main(int argc, char* argv[])
{
    // delete SHM if exists
    shared_memory_object::remove("my_shm");
    
    // create a new SHM object and allocate space
    managed_shared_memory managed_shm(open_or_create, "my_shm", 1024);

    test* i = managed_shm.construct<test>("my_solve")();
    i->pInt = new int; 
    *(i->pInt) = 2;
    
    return 0;
}

如何在receiver.cpp 中获得值2 (i->pInt)?我的receiver.cpp 看起来像这样:

int main(int argc, char* argv[])
{
    managed_shared_memory managed_shm(open_or_create, "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 << std::endl;
        std::cout << "print value ans->pInt: " << *(ans->pInt) << std::endl;
    }
    else
        std::cout << "my_solve not found" << '\n';

    managed_shm.destroy<test>("my_solve");
    // delete SHM if exists
    shared_memory_object::remove("my_shm");

    return 0;
}

我得到错误:

*(ans-&gt;pInt) 的读取访问冲突

提前致谢!

---------已更新----------

我通过这样的分配修复了 sender.cpp

    allocator<int, managed_shared_memory::segment_manager>int_alloc(managed_shm.get_segment_manager());
    test* i = managed_shm.construct<test>("my_solve")();
    auto allocated_ints = int_alloc.allocate(1); 
    i->pInt = allocated_ints.get();

但我仍然有同样的错误。我需要更改 receiver.cpp 中的任何内容吗?

【问题讨论】:

  • 你不能,test对象本身在共享内存中,但是你用new分配的int是你的进程内存,直接从另一个进程读取它会扰乱操作系统.你不能直接拥有intfloat 值吗?
  • @Kaldrr 哦,我明白了。这只是我对另一个项目的测试,我需要在结构中创建指针。那么你知道如何在共享内存中创建它吗?

标签: c++ pointers struct boost-interprocess


【解决方案1】:

由于您在receiver 进程中将pInt 分配给new int,因此它将包含一个仅在那里有效的地址。您正试图在 sender 进程中访问该地址,在该进程中它最好是未映射的,或者最坏的情况是指向一个完全不同的数据结构。

幸运的是,boost::interprocess 模块提供了allocators 为您在共享内存段内分配内存:

allocator<int, managed_shared_memory::segment_manager>
  allocator_instance(managed_shm.get_segment_manager());
auto allocated_ints = allocator_instance.allocate(100);
i->pInt = allocated_ints.get();

请注意,分配器仅限于一种类型,因此您需要为您的float* 使用第二个分配器。 另请参阅"quick guide for the impatient",了解在共享内存中分配std::vector&lt;int&gt; 的可复制粘贴示例。

【讨论】:

  • 我尝试了分配pInt 的示例代码,但出现错误:Error C2440 '=': cannot convert from 'boost::interprocess::offset_ptr&lt;U,DifferenceType,OffsetType,0&gt;' to 'int *'。有什么问题吗?
  • 显然您需要在返回的对象上调用.get() 以获取原始指针。见编辑。
  • 我需要更改 receiver.cpp 中的任何内容吗?我仍然收到相同的读取访问错误:((
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2013-10-07
  • 2022-01-08
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多