I would like to share an existing C++ array to other processes for manipulation. I can currently do that by copying it to boost/interprocess/shared_memory_object
and boost/interprocess/mapped_region
, i.e,
contrib_shm = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create,
contrib_mem_out.c_str(),
boost::interprocess::read_write);
contrib_shm.truncate(n * size_of_int);
boost::interprocess::mapped_region contrib_region(contrib_shm, boost::interprocess::read_write);
memcpy(contrib_region.get_address(), my_array_of_size_n, n* size_of_int);
I was wondering if I can do this:
contrib_shm = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create,
contrib_mem_out.c_str(),
boost::interprocess::read_write);
contrib_shm.truncate(n * size_of_int);
boost::interprocess::mapped_region contrib_region(contrib_shm, boost::interprocess::read_write, 0, n * sizeof(int), (void *)my_array_of_size_n);
Seems like I can: https://www.boost.org/doc/libs/1_55_0/doc/html/interprocess/sharedmemorybetweenprocesses.html
But when I try I keep getting library_error
.
No, you can’t.
With a little fore-thought you can, if you avoid putting the array on the heap (or stack) first. This obviously requires you to map the memory ahead of time.
I believe the memory hint you’re trying to use is just that: a hint. It will be platform dependent what the effect might be, but one thing is sure not to work: an address that is pointing in an area of the process already mapped (to the heap in this case) cannot be honoured.