我公开了一个要从中调用函数的类:
class_<MyClass, std::shared_ptr<MyClass>>("MyClass", init<>())
// ...
.def("someFunc", &MyClass::someFunc)
;
我从另一个通过.def_readonly(...)
公开的类的成员变量中获取std::shared_ptr<MyClass>
当我试图调用该函数时,出现以下错误:
File "pytest.py", line 27, in test_func
cu.someFunc("string")
Boost.Python.ArgumentError: Python argument types in
MyClass.someFunc(MyClass, str)
did not match C++ signature:
result(MyClass{lvalue}, std::string)
据我所见,签名是匹配的。 有人看到问题了吗?
还没有测试过,但这可能有效:
资料来源: http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/register_ptr_to_python.html
如本文ticket所述,Boost.Python不完全支持
std::shared_ptr
。简而言之,两个简单的解决方案是:
boost::shared_ptr
而不是std::shared_ptr
。add_property()
公开std::shared_ptr
成员变量,提供具有^{虽然异常中的签名看起来相同,但微妙的细节是Python
MyClass
对象嵌入了一个std::shared_ptr<MyClass>
。因此,Boost.Python必须执行从std::shared_ptr<MyClass>
到左值MyClass
的转换。但是,Boost.Python目前不支持custom lvalue conversions。因此,抛出ArgumentError
异常。使用
def_readonly("spam", &Factory::spam)
公开成员变量时,相当于通过以下方式公开:当以这种方式公开的类型是
boost::shared_ptr
时,Python有特殊的代码。由于它是只读属性并且std::shared_ptr
是要复制的,因此可以安全地公开具有返回值策略且类型为return_by_value
的std::shared_ptr
的副本。这里有一个完整的例子,其中
Factory
公开了std::shared_ptr
持有的Spam
对象和boost::shared_ptr
持有的Egg
对象:交互式Python演示用法和对象生存期:
相关问题 更多 >
编程相关推荐