【发布时间】: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->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是你的进程内存,直接从另一个进程读取它会扰乱操作系统.你不能直接拥有int和float值吗? -
@Kaldrr 哦,我明白了。这只是我对另一个项目的测试,我需要在结构中创建指针。那么你知道如何在共享内存中创建它吗?
标签: c++ pointers struct boost-interprocess