5

我们小组正在使用 C++ 开发一个数字框架。我们现在想包装我们框架的基本部分,以便在 Python 中可用。我们选择的武器是 Boost.Python,因为我们已经将 Boost 用于其他目的。我们只使用 smart_ptrs 来支持多态性。以下片段是我们如何应用策略模式的简单示例:

#include <boost/shared_ptr.hpp>
struct AbsStrategy
{
  virtual std::string talk( ) = 0;
};

typedef boost::shared_ptr<AbsStrategy> StrategyPtr;

struct Foo : AbsStrategy
{
  std::string talk( )
  {
    return "I am a Foo!";
  }
};

struct Bar : AbsStrategy
{
  std::string talk( )
  {
    return "I am a Bar!";
  }
};

struct Client
{
  Client( StrategyPtr strategy ) :
          myStrategy( strategy )
  {
  }

  bool checkStrategy( StrategyPtr strategy )
  {
    return ( strategy == myStrategy );
  }

  StrategyPtr myStrategy;
};

如果我像这样使用 Boost.Python 包装整个东西

#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE( BoostPython )
{
  class_<Foo>( "Foo" )
      .def( "talk", &Foo::talk );

  class_<Bar>( "Bar" )
      .def( "talk", &Bar::talk );

  class_<Client>( "Client", init<StrategyPtr>( ) )
      .def( "checkStrategy", &Client::checkStrategy );
}

编译时弹出以下警告

C:/boost/include/boost-1_51/boost/python/object/instance.hpp:14:36: warning: type attributes ignored after type is already defined [-Wattributes]

当我尝试在 python 中使用包装器时,出现以下错误

>>> from BoostPython import *
>>> foo = Foo()
>>> bar = Bar()
>>> client = Client(foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    Tree.__init__(Tree, Foo)
did not match C++ signature:
    __init__(_object*, boost::shared_ptr<AbsStrategy>)
>>> client = Client(bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    Tree.__init__(Tree, Bar)
did not match C++ signature:
    __init__(_object*, boost::shared_ptr<AbsStrategy>)

在不改变我们的框架的情况下让整个事情工作起来缺少什么?当然,包装器可以自由调整。

4

1 回答 1

4

好的,我找到了解决方案。一个必须implicitly_convertible在模块声明中使用,如下所示。

#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE( BoostPython )
{
  class_<Foo>( "Foo" )
      .def( "talk", &Foo::talk );

  class_<Bar>( "Bar" )
      .def( "talk", &Bar::talk );

  class_<Client>( "Client", init<StrategyPtr>( ) )
      .def( "checkStrategy", &Client::checkStrategy );

  implicitly_convertible<boost::shared_ptr<Foo> , StrategyPtr>();
  implicitly_convertible<boost::shared_ptr<Bar> , StrategyPtr>();
}
于 2013-01-24T13:23:52.157 回答