简体   繁体   English

复制std :: vector到boost :: interprocess :: vector

[英]Copy std::vector to boost::interprocess::vector

I want to share vector of objects using boost interprocess. 我想使用boost进程共享对象向量。 The objects are from the following structure: 这些对象来自以下结构:

struct Foo
    {
        int id;
        float time;
        bool isFoo;

        float myArray[7];

        std::vector<int> vectorData;
    };

I am creating boost inter process allocator and inter process vector: 我正在创建boost进程间分配器和进程间向量:

typedef allocator<Foo, managed_shared_memory::segment_manager>  FooAllocator;

typedef std::vector<Foo, FooAllocator> FooVector;

In my main function i initialize the memory segment, the allocator and the vector, based on: 在我的主要功能中,我基于以下内容初始化内存段,分配器和向量:

boost -> creating vectors in shared memory boost->在共享内存中创建向量

so: 所以:

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

Now, this is working for every data type in the Foo structure except vector. 现在,这适用于Foo结构中除vector外的所有数据类型。 So if i try to share this i get all the members from Foo, and for vector data i get "Undefined memory location" I know that std::vector can't be shared directly. 因此,如果我尝试共享它,我将从Foo中获取所有成员,对于矢量数据,我将获得“未定义的内存位置”,我知道std :: vector无法直接共享。 So i created new Foo structure with boost::interprocess:vector 所以我用boost :: interprocess:vector创建了新的Foo结构

struct FooInter
    {
        int id;
        float time;
        bool isFoo;

        float myArray[7];
        MyVector* pointcloud;
    };

Where MyVector is: MyVector在哪里:

typedef allocator<int, managed_shared_memory::segment_manager> VectorAllocator;
typedef boost::interprocess::vector<int, VectorAllocator> MyVector;

I am allocating memory for MyVector, 我正在为MyVector分配内存,

const VectorAllocator vec_alloc_inst(mem_segment.get_segment_manager());
MyVector* tmpVec = mem_segment.construct<MyVector>("MyVector")(vec_alloc_inst);

then what i try to do now is map the Foo to FooInter. 那么我现在要做的是将Foo映射到FooInter。 I am mapping the vector data in for loop: 我在for循环中映射矢量数据:

    for (int t = 0; t < foo.vectorData.size()-1; t++) {
        tmpVec->push_back(foo.vectorData[t]);
    }

And then copy the tmpVec into fooInter.vectorData: 然后将tmpVec复制到fooInter.vectorData中:

memcpy(fooInter.pointcloud, tmpVec, sizeof(int) * tmpVec->size());

This works but not for the whole size of foo.vectorData. 这是可行的,但不适用于foo.vectorData的整个大小。 So it works for 100 items, but if i go with foo.vectorData.size() it returns bad memory alloc. 因此它适用于100个项目,但是如果我使用foo.vectorData.size(),它将返回错误的内存分配。

Can somebody help me with this. 有人可以帮我这个忙吗? I need to know the proper way to share a structure of this type. 我需要知道共享这种类型结构的正确方法。 I feel that what i am doing is entirely wrong. 我觉得我在做什么是完全错误的。 Maybe i need to serialize the vector into string or something similar. 也许我需要将向量序列化为字符串或类似的东西。

Edit: 编辑:

Based on the answer from sehe: 根据sehe的回答:

I have object msg from type: 我有来自类型的对象味精:

struct Foo
    {
        int id;
        float time;
        bool isFoo;

        float myArray[7];

        std::vector<int> pointcloud;
    };

i need to pass that object in inter_foos. 我需要在inter_foos中传递该对象。 So in the code from sehe: 所以在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"; 
}

I cannot imagine that using memcpy to copy a MyVector is going to work well. 我无法想象使用memcpy复制MyVector会很好地工作。 Surely what you need is: 当然您需要的是:

void FooInter::setVector(const std::vector<int>& vec) {
    const VectorAllocator vec_alloc_inst(mem_segment.get_segment_manager());
    const auto tmp = mem_segment.construct<MyVector>("MyVector")(vec_alloc_inst);
    tmp->insert(tmp->begin(), vec.begin(), vec.end());
    pointcloud = tmp;
}

In other words, construct the object pointed to by pointcloud, and then insert into it. 换句话说,构造由点云指向的对象,然后将其插入其中。

You can use the approach from 您可以使用以下方法

See this Demo¹ 观看此演示¹

Live On Coliru 生活在Coliru

#include <boost/interprocess/managed_shared_memory.hpp>

#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/container/scoped_allocator.hpp>

#include <iostream>
#include <vector>

namespace Shared {
    namespace bip = boost::interprocess;
    namespace bc  = boost::container;

    using Segment                     = bip::managed_shared_memory;
    using Manager                     = Segment::segment_manager;
    template <typename T> using Alloc = bc::scoped_allocator_adaptor<bip::allocator<T, Manager> >;
    template <typename T> using Vector= bip::vector<T, Alloc<T> >;

    Segment open() { return { bip::open_or_create, "MySharedMemory", 10ul<<20 }; }

    template <typename Alloc = Alloc<void> >
    struct Foo {
        using allocator_type = typename Alloc::template rebind<Foo>::other;
        using Ints = bip::vector<int, typename Alloc::template rebind<int>::other>;

        Foo(int id, float time, bool isFoo = false, std::initializer_list<float> floats = {}, Ints data = {})
            : id(id), time(time), isFoo(isFoo), vectorData(std::move(data))
        {
            std::copy_n(floats.begin(), std::min(floats.size(), 7ul), myArray);
        }

        template <typename OA, typename A>
        Foo(Foo<OA> const& other, A alloc = {}) 
            : id(other.id), time(other.time), isFoo(other.isFoo),
              vectorData(other.vectorData.begin(), other.vectorData.end(), alloc)
        {
            std::copy(std::begin(other.myArray), std::end(other.myArray), myArray);
        }

        int   id;
        float time;
        bool  isFoo;
        float myArray[7] = {};
        Ints  vectorData;
    };

    template <typename A>
    std::ostream& operator<<(std::ostream& os, Foo<A> const& f) {
        os << "{" 
           << f.id << ", "
           << std::fixed << f.time << ", "
           << std::boolalpha << f.isFoo << ", "
           << "[";

        std::copy(std::begin(f.myArray), std::end(f.myArray), std::ostream_iterator<float>(std::cout, ";"));
        os << "], [";
        std::copy(std::begin(f.vectorData), std::end(f.vectorData), std::ostream_iterator<int>(std::cout, ";"));
        return os << "] }";
    }

}

using Foo       = Shared::Foo<std::allocator<void> >;
using InterFoo  = Shared::Foo<>;

using InterFoos = Shared::Vector<InterFoo>;
using Ints      = Shared::Vector<int>;

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();
    inter_foos.push_back({++nextid, 0, true, {.1,.2,.3,.4,.5,.6,.7}, Ints ({10,20,30}, segment.get_segment_manager()) });

    // 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"; 
}

Prints: 打印:

{1, 0.000000, true, [0.100000;0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;], [10;20;30;] }
{2, 0.000000, true, [0.100000;0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;], [10;20;30;] }
{3, 1.000000, true, [0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;0.800000;], [20;30;40;] }
{4, 2.000000, true, [0.300000;0.400000;0.500000;0.600000;0.700000;0.800000;0.900000;], [30;40;50;] }

Second run: 第二轮:

{1, 0.000000, true, [0.100000;0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;], [10;20;30;] }
{2, 0.000000, true, [0.100000;0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;], [10;20;30;] }
{3, 1.000000, true, [0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;0.800000;], [20;30;40;] }
{4, 2.000000, true, [0.300000;0.400000;0.500000;0.600000;0.700000;0.800000;0.900000;], [30;40;50;] }
{5, 0.000000, true, [0.100000;0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;], [10;20;30;] }
{6, 0.000000, true, [0.100000;0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;], [10;20;30;] }
{7, 1.000000, true, [0.200000;0.300000;0.400000;0.500000;0.600000;0.700000;0.800000;], [20;30;40;] }
{8, 2.000000, true, [0.300000;0.400000;0.500000;0.600000;0.700000;0.800000;0.900000;], [30;40;50;] }

Scoped Allocators 范围分配器

Note that this: 注意:

    for (auto& local_foo : local)
        inter_foos.emplace_back(local_foo);

works because of scoped allocators being supported and passed along by Boost's container implementations. 之所以能够工作,是因为Boost的容器实现支持并传递了范围内的分配器。 If you didn't use it, thing would look like this: Live On Coliru 如果您不使用它,则内容将如下所示: Live On Coliru

template <typename T> using Alloc = bip::allocator<T, Manager>;
// ...

for (auto& local_foo : local)
    inter_foos.emplace_back(local_foo, segment.get_segment_manager());

¹ using mapped file because shared memory is not supported on COLIRU ¹使用映射文件,因为COLIRU不支持共享内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM