I am new to boost library. I am trying to use boost::interprocess to allocate a very simple data structure in shared memory. My struct looks like this:
struct test {
int* pInt;
float* pFloat;
};
Here is 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;
}
How can I get the value 2 (i->pInt) in receiver.cpp? My receiver.cpp looks like this:
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;
}
And I get error:
read access violation with
*(ans->pInt)
Thanks in advance!
----------UPDATED----------
I fixed in sender.cpp by allocating like this:
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();
But I still have the same error. Do I need to change anything in receiver.cpp?