免责声明:是的,我知道约boost::python::map_indexing_suite
。如何包装一个C++类与构造函数一个std ::地图或std :: vector的说法并带有Boost.Python?
任务:我有一个C++类,我想用Boost.Python包装。它的构造函数需要一个std::map
参数。下面是C++头:
// myclass.hh
typedef std::map<int, float> mymap_t;
class MyClass {
public:
explicit MyClass(const mymap_t& m);
// ...
};
// ...
这里是Boost.Python的包装物(仅主要部分):
// myclasswrapper.cc
#include "mymap.hh"
#include "boost/python.hpp"
#include "boost/python/suite/indexing/map_indexing_suite.hpp"
namespace bpy = boost::python;
// wrapping mymap_t
bpy::class_<mymap_t>("MyMap")
.def(bpy::map_indexing_suite<mymap_t>())
;
// wrapping MyClass
bpy::class_<MyClass>("MyClass", "My example class",
bpy::init<mymap_t>() // ??? what to put here?
)
// .def(...method wrappers...)
;
这将编译。但是,我不能从Python端创建映射MyClass
对象,因为我不知道该怎么传递作为参数传递给构造。字典没有被转换到自动std::map
-s:
# python test
myclass = MyClass({1:3.14, 5:42.03})
解释抱怨(这是正确的):
Boost.Python.ArgumentError: Python argument types in
MyClass.__init__(MyClass, dict)
did not match C++ signature:
__init__(_object*, std::__1::map<int, float, ...
和MyMap
在Python端不能与字典或者初始化。
已经用Google搜索了好几天,最精彩的部分,我能找到的唯一采取的是映射与.def(...)
std::map
参数“正常”的方法的例子。并且在.def(...)
中,您不必明确指定映射方法的参数,它们被神奇地发现。使用构造函数,您必须使用boost::python::init<...>()
,或者至少这是我从文档中理解的。
问题:
- 要我补充一下到
MyMap
包装,以帮助map_indexing_suite
转换从Python字典? - 我应当用
MyClass
包装在boost::python::init<...>
不同的模板参数? - 任何其他的想法...?
注意:我也看到this accepted answer at SO,然后我向下滚动和读取@YvesgereY评论:
“为了记录在案,map_indexing_suite解决方案不起作用,因为没有 隐“dict-> std :: map”from_python转换器将被应用。“
,我失去了信心:-)
做一个独立的函数,它将构造'boost :: python :: dict'对象。见[这个答案](http://stackoverflow.com/a/18793953/3962537)的灵感。 –
@DanMašek:非常感谢,您的评论非常有用,它指向了转换器。我现在回答我自己的问题,见下文。 –