我知道boost interprocess containers,示例使用托管共享内存。但我想使用一个简单的boost::interprocess::shared_memory_object
,其中有一个对象,以及该对象中的向量或任何其他容器。这似乎不起作用。
试过这个:
#include <stack>
#include <boost/interprocess/containers/vector.hpp>
namespace bip = boost::interprocess;
class SharedMemoryMetadata
{
public:
std::stack<unsigned short> newData;
int deleteme;
bip::vector<unsigned short> v;
};
并使用以下命令创建共享内存:
bip::shared_memory_object::remove(OUTPUT_METADATA_MEMORY_SEGMENT_NAME);
sharedMemoryMetadataForOutput = new bip::shared_memory_object(bip::create_only, OUTPUT_METADATA_MEMORY_SEGMENT_NAME, bip::read_write);//use old shared memory if exists else create a new one
sharedMemoryMetadataForOutput->truncate(sizeof(SharedMemoryMetadata)+ (3*sizeof(unsigned int)*MAX_NUMBER_OF_OBJECTS_EXPECTED_TO_BE_IN_SHARED_MEMORY));//set the size of the memory object
sharedMemoryMetadataRegion = new bip::mapped_region(*sharedMemoryMetadataForOutput, bip::read_write);//map the whole shared memory in this process
void* sharedMemorySegmentForMetadataStorage = sharedMemoryMetadataRegion->get_address();//get the region address
sharedMemoryMetadataObject = new (sharedMemorySegmentForMetadataStorage) SharedMemoryMetadata();//create a shared memory buffer in memory
我尝试使用以下方式访问它:
bip::shared_memory_object* sharedMemoryMetadataForOutput;
SharedMemoryMetadata* sharedMemoryMetadataObject;
bip::mapped_region* sharedMemoryMetadataRegion;
bip::shared_memory_object* sharedMemoryMetadataForOutput;
SharedMemoryMetadata* sharedMemoryMetadataObject;
bip::mapped_region* sharedMemoryMetadataRegion;
sharedMemoryMetadataForOutput = new bip::shared_memory_object(bip::open_only, OUTPUT_METADATA_MEMORY_SEGMENT_NAME, bip::read_write);//create a shared memory object http://blog.wolfgang-vogl.com/?p=528
sharedMemoryMetadataRegion = new bip::mapped_region(*sharedMemoryMetadataForOutput, bip::read_write);//Map the whole shared memory in this process
void * sharedMemorySegmentForMetadataStorage = sharedMemoryMetadataRegion->get_address();//get the region address
sharedMemoryMetadataObject = static_cast<SharedMemoryMetadata*>(sharedMemorySegmentForMetadataStorage);//Obtain the shared structure
正如预期的那样,即使写入堆栈的内容,std::stack<unsigned short> newData;
也是空的。但是如果我为int deleteme
分配一个值,我就能从另一个访问共享内存的程序中读取它。
push_back
到bip::vector<unsigned short> v;
有效,但是当我尝试从其他程序访问它时,我遇到了分段错误。有没有办法可以在shared_memory_object
中存储和访问向量,或者只使用托管共享内存?即使我使用托管共享内存,如何将向量存储在SharedMemoryMetadata
类中,如上所示?