【发布时间】:2018-05-13 05:33:44
【问题描述】:
Boost Python 1.63 (python 2.7.13) 与shared_ptr<T> 配合得很好;如果我用 C++ 编写:
shared_ptr<Foo> create_shared_ptr() { return shared_ptr{...}; }
void accept_shared_ptr(const shared_ptr<Foo>& p) { }
...
class_<Foo, boost::noncopyable>("Foo", no_init); //Expose abstract class
register_ptr_to_python< shared_ptr<Foo> >();
def("create_shared_ptr", create_shared_ptr);
def("accept_shared_ptr", accept_shared_ptr);
然后我可以用 Python 编写这个并且一切正常:
accept_shared_ptr(create_shared_ptr())
当我尝试包装 shared_ptr<const Foo> 时,问题就来了。(我需要这样做,因为我正在包装一个返回它的库。)如果我如下修改 C++ 函数: p>
shared_ptr<const Foo> create_shared_ptr() { return shared_ptr{...}; }
void accept_shared_ptr(const shared_ptr<const Foo>& p) { }
然后我得到错误:
Boost.Python.ArgumentError: Python argument types in mod_python.accept_shared_ptr(Foo) did not match C++ signature: accept_shared_ptr(std::shared_ptr<Foo const>)
内部似乎正在实现从 python Foo 到 C++ shared_ptr<Foo> 的转换,而不是到 C++ shared_ptr<const Foo> 的转换。使用
register_ptr_to_python< shared_ptr<const Foo> >();
没有帮助。我该如何解决这个问题?
【问题讨论】:
-
致投票结束的人:以下基于 boost 1.62 的答案并不能解决问题。 2016 年 9 月 23 日有一个提交
Add support for std::shared_ptr.。Boost 1.62 于 9 月 1 日发布,1.62 于 11 月 2 日发布。(github.com/boostorg/python/commit/…)。这个提交有可能破坏了一些东西。 -
请包含命名空间,不清楚您使用的是 std::shared_ptr 还是 boost_shared_ptr
标签: python c++ boost constants shared-ptr