通过引用传递时std::vector的转换器

Converter for std::vector when passed by reference

本文关键字:vector 转换器 std 引用      更新时间:2023-10-16

这是std::vector to boost::python::list

我尝试了提供的示例:

// C++ code
typedef std::vector<std::string> MyList;
class MyClass {
   MyList myFuncGet();
   void myFuncSet(MyList& list)
   {
      list.push_back("Hello");
   }
};
// My Wrapper code
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(mymodule)
{
    class_<MyList>("MyList")
        .def(vector_indexing_suite<MyList>() );
    class_<myClass>("MyClass")
        .def("myFuncGet", &MyClass::myFuncGet)
        .def("myFuncSet", &MyClass::myFuncSet)
        ;
}

但当我尝试在Python中实际使用它时,我会遇到一个错误(见底部)。

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from mymoduleimport *
>>> mc = MyClass()
>>> p = []
>>> mc.myFuncSet(p)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    MyClass.myFuncSet(MyClass, list)
did not match C++ signature:
myFuncSet(MyClass {lvalue}, std::vector<std::string, std::allocator<std::string> > {lvalue})

根据我通过阅读其他网站收集到的信息;员额,需要一个转换器。有人能通过添加必要的转换器代码来完成我的示例吗?我会自己做,但我对boost不够熟悉,不知道这样的转换器是什么样子的。

提前感谢!

我相信只有在通过值或常量引用传递参数时才能使用转换器。传递非一致引用要求直接暴露类型。这意味着,如果您想在不复制列表项的情况下将列表从python传递到c++,则需要更改代码以使用boost::python::list而不是MyList,后者类似于(未经测试的)

void myFuncSet(boost::python::list& list)
{
   list.append("Hello");
}

矢量索引套件将类似python列表的行为添加到MyList绑定中,它不允许您在其位置传递python列表。

您在示例中遇到的错误是,您试图将python列表传递给使用std::vector<int>的函数。我怀疑这会起作用

p = mc.myFuncGet()
mc.myFuncSet(p)

这是一篇关于编写转换器的非常有用的文章。http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/