c++ - boost::python 函数调用中 boost::shared_ptr 的转换

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

考虑以下示例:

#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})

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

最佳答案

问题是您要求对 shared_ptr<A> 的非常量引用,还有你的 b Python 中的实例根本不包含一个;它包含一个 shared_ptr<B> .同时 shared_ptr<B>可以隐式转换为 shared_ptr<A> , shared_ptr<B>& 不能隐式转换为shared_ptr<A>& .

如果可以修改foo采取shared_ptr<A> , 或 shared_ptr<A> const & ,这将解决您的问题。

如果没有,您还需要包装一个接受 shared_ptr<B>& 的版本.

关于c++ - boost::python 函数调用中 boost::shared_ptr 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10656954/

相关文章:

python - Django TemplateTags 不编译

c++ - Boost 字符串处理函数是否曾经持有全局锁?

c++ - 两张 map 不匹配

c++ - 为什么写入我的字符串不起作用?

c++ - 每个编译单元是否只有一个未命名的命名空间?

python - 从map()返回不同的变量

python - 无法让看门狗观察者停止/加入(python)

c++ - 是否可以使用单独的线程来读取和写入 Boost.Asio?

c++ - boost 定时器使用问题

c++ - 采用指向基类的指针的函数是否也接受从基类私有(private)派生的子类?