C++: boost::interprocess 内存映射文件错误

标签 c++ boost memory-mapped-files interprocess

我正在尝试使用 this 创建内存映射文件回答,但我收到编译错误。这是我的代码:

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);

结构是这样的:

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];
}

我得到的错误是:编译器无法从“boost::interprocess::offset_ptr”推断出“_Ty*”的模板参数。我做错了什么?

最佳答案

我觉得没问题:

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());
}

如果它不能完全按照上面的方式编译,请注意您的库和编译器的版本。考虑升级。

关于C++: boost::interprocess 内存映射文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822114/

相关文章:

c++ - 使用 boost python 和 python 3.2 的 Hello world

c++ - 通过延迟的 self 转换来 boost MSM并行行为?

c# - 使用内存映射 View 查看大位图图像

c++ - Boost::C++ 数据复制的信号

c++ - 我应该如何使用X11、motif、DrawingArea和c++设置DrawingArea(X,Y)坐标(0,0)

c++ - boost::spirit:如何编写一个解析器来解析 2 个字符串并将它们 'combined' 变成一个?

c++ - 结构 vector 上的 MemCpy

c++ - 独立 DLL 之间的内部进程通信

c++ - 如何在不改变元素顺序的情况下合并两个unordered_map?

c++ - 释放内存映射文件后取消映射 View 是否安全?