mardi 24 octobre 2017

Allocating a user defined struct in shared memory with boost::interprocess

I am trying to use boost::interprocess to allocate a very simple data structure in shared memory but I cannot quite figure out how to use the allocators to perform the memory allocations/deallocations within the shared memory segment.

I previously asked a similar question but unfortunately I never got any answers. MyStruct below is essentially an array with a length field indicating the size of the array. For now I have a simple length field but I will add some other constructor arguments later (bool's and other simple types).

In order to allocate this in the shared memory segment, I know I have to do something with allocators but I cannot find a similar example where I have a user defined type containing an array/pointer field.

    using MyType = struct MyType {
        explicit MyType(const size_t aSize)
            : mSize(aSize)
            , mpData(new char[aSize])
        {}

        ~MyType() {
            delete[]mpData;
        }
        size_t mSize;
        char * mpData;
    };

    using MyTypeAllocator = boost::interprocess::allocator<MyType,
        boost::interprocess::managed_shared_memory::segment_manager>;

    // Initialize the shared memory STL-compatible allocator
    MyTypeAllocator alloc(mSharedMemory->get_segment_manager());

Aucun commentaire:

Enregistrer un commentaire