简体   繁体   English

std :: vector以boost :: python :: list而不复制数据

[英]std::vector to boost::python::list without copy the data

My question is basically the same as std::vector to boost::python::list . 我的问题基本上与将std :: vector提高到boost :: python :: list相同 The difference is that I only need to read data from C++ in python side. 不同之处在于,我只需要在python端从C ++ 读取数据。

Naively, I could build a new C++ class holding a pointer and forward all the required attributes and then expose this new class to python. 天真的,我可以构建一个新的C ++类,其中包含一个指针并转发所有必需的属性,然后将此新类公开给python。 Is there a better(simpler or systematic) way to get a python 'list' (not really a list since setter is not allowed) without copy the underlying data? 有没有一种更好的(简单或系统的)方式来获取python“列表”(由于不允许使用setter,所以实际上不是列表)而不复制基础数据?

If you do not want to convert std::vector to boost::python::list . 如果您不想将std::vector to boost::python::list转换std::vector to boost::python::list Then it can be possible if you pass the size of vector to python side and iterate the function with argument as index to get the element of vector to python side. 然后,可以将vector的大小传递给python端,并以参数作为索引迭代该函数以将vector的元素传递到python端。

in cpp: 在cpp中:

class vc
{
    private:
        vector <int> vec ;
    public: 
        vc(){};
        void set_vector();
        int vector_size();
        int vector_iterator(int index);
        ~vc(){};
}

void vc::set_vector()
{
    for(int i=0;i<10;i++)
        this->vec.push_back(i);
}

int vc::vector_size()
{   
    return this->vec.size();
}

int vc::vector_iterator(int index)
{   
    if(this->vec.size()> index)
        return  this->vec[index];
    return 0;
}

BOOST_PYTHON_MODULE(vector_imp)  
{  
    class_<vc>("vc", init<>())
        .def("set_vector",&vc::set_vector)
        .def("vector_size",&vc::vector_size)  
        .def("vector_iterator",&vc::vector_iterator)
    ;  
}

in python: 在python中:

import vector_imp as vect
    vc_obj = vect.vc()
    vc_obj.set_vector()
    v_size = vc_obj.vector_size()
    for i in range(0,v_size):
        element = vc_obj.vector_iterator(i)
        print element

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

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