【发布时间】:2018-07-24 17:08:23
【问题描述】:
我想使用 boost 进程间共享对象向量。对象来自以下结构:
struct Foo
{
int id;
float time;
bool isFoo;
float myArray[7];
std::vector<int> vectorData;
};
我正在创建 boost 进程间分配器和进程间向量:
typedef allocator<Foo, managed_shared_memory::segment_manager> FooAllocator;
typedef std::vector<Foo, FooAllocator> FooVector;
在我的主函数中,我初始化内存段、分配器和向量,基于:
boost -> creating vectors in shared memory
所以:
managed_shared_memory mem_segment(open_or_create, "MemShare", 65536);
const FooAllocator alloc_inst(mem_segment.get_segment_manager());
fooVector = mem_segment.find_or_construct<FooVector>("FooVector")(alloc_inst);
现在,这适用于 Foo 结构中除向量之外的所有数据类型。因此,如果我尝试分享这个,我会从 Foo 中获取所有成员,而对于矢量数据,我会得到“未定义的内存位置” 我知道 std::vector 不能直接共享。所以我用 boost::interprocess:vector 创建了新的 Foo 结构
struct FooInter
{
int id;
float time;
bool isFoo;
float myArray[7];
MyVector* pointcloud;
};
MyVector 在哪里:
typedef allocator<int, managed_shared_memory::segment_manager> VectorAllocator;
typedef boost::interprocess::vector<int, VectorAllocator> MyVector;
我正在为 MyVector 分配内存,
const VectorAllocator vec_alloc_inst(mem_segment.get_segment_manager());
MyVector* tmpVec = mem_segment.construct<MyVector>("MyVector")(vec_alloc_inst);
然后我现在尝试做的是将 Foo 映射到 FooInter。我在 for 循环中映射矢量数据:
for (int t = 0; t < foo.vectorData.size()-1; t++) {
tmpVec->push_back(foo.vectorData[t]);
}
然后将tmpVec复制到fooInter.vectorData中:
memcpy(fooInter.pointcloud, tmpVec, sizeof(int) * tmpVec->size());
这有效,但不适用于 foo.vectorData 的整个大小。所以它适用于 100 个项目,但如果我使用 foo.vectorData.size() 它会返回错误的内存分配。
有人可以帮我解决这个问题吗?我需要知道共享这种类型结构的正确方法。我觉得我所做的是完全错误的。也许我需要将向量序列化为字符串或类似的东西。
编辑:
根据sehe的回答:
我有来自类型的对象消息:
struct Foo
{
int id;
float time;
bool isFoo;
float myArray[7];
std::vector<int> pointcloud;
};
我需要在 inter_foos 中传递该对象。所以在sehe的代码中:
int main() {
auto segment = Shared::open();
auto& inter_foos = *segment.find_or_construct<InterFoos>("InterFoos")(segment.get_segment_manager());
// you can directly append to the shared memory vector
int nextid = inter_foos.size();
//instead of this
inter_foos.push_back({++nextid, 0, true, {.1,.2,.3,.4,.5,.6,.7}, Ints ({10,20,30}, segment.get_segment_manager()) });
//i need this
inter_foos.push_back({msg.id, msg.time, true, msg.myArray, Ints (msg.pointcloud, segment.get_segment_manager()) });
//i can't pass msg.poincloud to this object!!!
// or copy from a non-shared vector:
std::vector<Foo> const local {
{++nextid, 0, true, {.1,.2,.3,.4,.5,.6,.7}, {10,20,30} },
{++nextid, 1, true, {.2,.3,.4,.5,.6,.7,.8}, {20,30,40} },
{++nextid, 2, true, {.3,.4,.5,.6,.7,.8,.9}, {30,40,50} },
};
for (auto& local_foo : local)
inter_foos.emplace_back(local_foo);
// print the current contents
for (auto& foo : inter_foos)
std::cout << foo << "\n";
}
【问题讨论】:
标签: c++ vector boost dynamic-memory-allocation interprocess