【问题标题】:conversion of boost::shared_ptr in boost::python function callboost::python 函数调用中 boost::shared_ptr 的转换
【发布时间】:2012-05-18 17:13:37
【问题描述】:

考虑以下示例:

#include "Python.h"
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>

class A {};

class B : public A{};

void foo(boost::shared_ptr<A>& aptr) { }

BOOST_PYTHON_MODULE(mypy)
{
  using namespace boost::python;   
  class_<A, boost::shared_ptr<A> >("A", init<>());
  class_<B, boost::shared_ptr<B>, bases<A> >("B", init<>());
  def("foo", foo);
}

如果我调用 python 代码

import mypy
b = mypy.B()
mypy.foo(b)

我明白了

ArgumentError: Python argument types in
    mypy.foo(B)
did not match C++ signature:
    foo(boost::shared_ptr<A> {lvalue})

我已经用谷歌搜索了很多,但我找不到很好的解释/修复/解决方法。非常欢迎任何帮助!

【问题讨论】:

  • 如果 foo 采用 boost::python::object 参数,然后从中提取 shared_ptr 会发生什么?
  • 当然可以,但我希望有一种方法可以不用为 foo 编写任何额外的包装器(我需要很多包装器)

标签: c++ python boost shared-ptr boost-python


【解决方案1】:

问题是您要求对shared_ptr&lt;A&gt; 进行非常量引用,而您在Python 中的b 实例根本不包含一个;它包含一个shared_ptr&lt;B&gt;。虽然shared_ptr&lt;B&gt; 可以隐式转换为shared_ptr&lt;A&gt;,但shared_ptr&lt;B&gt;&amp; 不能隐式转换为shared_ptr&lt;A&gt;&amp;

如果您可以将foo 修改为shared_ptr&lt;A&gt;shared_ptr&lt;A&gt; const &amp;,那将解决您的问题。

如果没有,您还需要包装一个接受 shared_ptr&lt;B&gt;&amp; 的版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    相关资源
    最近更新 更多