Search code examples
c++boostmemory-mapped-filesinterprocess

C++: Boost interprocess memory mapped file error


I'm trying to create a memory mapped file using this answer, but I'm getting compile errors. This is my code:

namespace bi = boost::interprocess;
std::string vecFile = "vector.dat";
bi::managed_mapped_file file_vec(bi::open_or_create,vecFile.c_str(), sizeof(struct Rectangle) * data_size);

typedef bi::allocator<struct Rectangle, bi::managed_mapped_file::segment_manager> rect_alloc;
typedef std::vector<struct Rectangle, rect_alloc>  MyVec;

MyVec * vecptr = file_vec.find_or_construct<MyVec>("myvector")(file_vec.get_segment_manager());

vecptr->push_back(random_rectangle);

The struct is this:

struct Rectangle{

  Rectangle(float *minArr, float *maxArr, int arr, int exp, int ID){
    this->arrival = arr;
    this->expiry = exp;
    this->id = ID;
    for(int i=0; i < 2; i++){
      min[i] = minArr[i];
      max[i] = maxArr[i];
    }

  int arrival, expiry, id;
  float min[2];
  float max[2];
}

The error I get is: Compiler could not deduce the template argument for '_Ty*' from 'boost::interprocess::offset_ptr'. What am I doing wrong?


Solution

  • It looks okay to me:

    Live On Coliru

    #include <boost/interprocess/managed_mapped_file.hpp>
    #include <vector>
    
    namespace bi = boost::interprocess;
    
    struct Rectangle {
        Rectangle(float *minArr, float *maxArr, int arr, int exp, int ID) {
            this->arrival = arr;
            this->expiry = exp;
            this->id = ID;
            for (int i = 0; i < 2; i++) {
                min[i] = minArr[i];
                max[i] = maxArr[i];
            }
        };
    
        int arrival, expiry, id;
        float min[2];
        float max[2];
    };
    
    namespace Shared {
        using segment = bi::managed_mapped_file;
        using mgr     = segment::segment_manager;
    
        using alloc   = bi::allocator<Rectangle, mgr>;
        using vector  = std::vector<Rectangle, alloc>;
    }
    
    Rectangle random_rectangle() { 
        float dummy[2] = { };
        return { dummy, dummy, 0, 0, 0 }; 
    }
    
    int main() {
    #define data_size 10
        std::string vecFile = "vector.dat";
        Shared::segment mmem(bi::open_or_create, vecFile.c_str(), (10u<<10) + sizeof(struct Rectangle) * data_size);
    
        Shared::vector *vecptr = mmem.find_or_construct<Shared::vector>("myvector")(mmem.get_segment_manager());
    
        vecptr->push_back(random_rectangle());
    }
    

    If it doesn't compile exactly as above, please note versions of your library and compiler. Consider upgrading.