boost-python-wrappec++类私有成员

boost python wrap c++ class private member

本文关键字:成员 boost-python-wrappec++      更新时间:2023-10-16

我们可以用boost python包装c++私有构造函数吗?我有一个单独的c++类,希望将它包装到python中。

我们可以用boost python包装c++私有成员函数吗?

非常感谢

使用类似的东西:

#include <boost/python.hpp>
#include <iostream>
using namespace boost::python;
using std::cout;
class Singleton
{
    private:
        Singleton()
        {
            cout << "Creating instancen";
        }
    friend Singleton* create(); 
};
Singleton* pInstance_;
Singleton* create()
{       
    if(!pInstance_)
    {
        pInstance_ = new Singleton();
    }
    else
    {
        cout << "Using old instancen";         
    }       
    return pInstance_;
}
BOOST_PYTHON_MODULE(cppmodule)
{
    def("create", create, return_value_policy<reference_existing_object>());
    class_<Singleton>("Singleton", no_init);
}
/* using singleton later in code */
Singleton* otherInstance_ = create();

会话:

>>> import cppmodule
Creating instance
>>> s = cppmodule.Singleton()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: This class cannot be instantiated from Python
>>> s = cppmodule.create()
Using old instance

singleton通常会用私有可见性声明其构造函数,并提供一个可以访问私有构造函数的工厂函数。

class singleton
{
public:
  /// @brief Public factory function.
  static singleton& instance()
  {
    static singleton instance_;
    return instance_;
  }
private:
  // Private constructors and destructor.
  singleton()  {}
  ~singleton() {};
  singleton(const singleton&);
  singleton& operator=(const singleton&);
};

默认情况下,Boost.Python假定一个公共可用的构造函数,该构造函数与提供给boost::python::class_构造函数的init表达式相匹配。为了抑制这种行为,可以向class_构造函数提供特殊的boost::python::no_init对象。此外,由于私有析构函数,class_需要通过提供boost::noncopyable作为模板参数来公开为不可复制。

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<singleton, boost::noncopyable>("Singleton", python::no_init);
}

在Python中,singleton很少通过其API将自己显示为singleton。因此,许多Python开发人员可能自然希望能够通过example.Singleton()实例化Python类,而不是使用factor方法。虽然默认构造函数已通过python::no_init公开,但可以为__init__定义自定义构造函数。为了正确解释C++单例,通过Boost.Python公开的单例将使用带有无操作deleter的boost::shared_ptr来保存单例的句柄。下面是一个完整的例子:

#include <boost/python.hpp>
/// @brief Mock up singleton class.
class singleton
{
public:
  /// @brief Public factory function.
  static singleton& instance()
  {
    static singleton instance_;
    return instance_;
  }
  void set_x(unsigned int x) { x_ = x;    }
  unsigned int get_x()       { return x_; }
private:
  // Private constructors and destructor.
  singleton() : x_(0) {}
  ~singleton() {};
  singleton(const singleton&);
  singleton& operator=(const singleton&);
private:
  unsigned int x_;
};
/// @brief No operation deleter.
void noop_deleter(void*) {};
/// @brief Helper function used to get a shared_ptr that holds
///        a singleton.
boost::shared_ptr<singleton> py_get_singleton()
{
  return boost::shared_ptr<singleton>(
    &singleton::instance(), // the instance
    &noop_deleter);         // no-op deleter
}
BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  // Expose the singleton class, supressing the default constructor
  // via python::no_init, and providing a constructor that will return
  // a handle to the singleton.
  python::class_<singleton, boost::shared_ptr<singleton>,
                 boost::noncopyable>("Singleton", python::no_init)
    .def("__init__", python::make_constructor(&py_get_singleton))
    .add_property("x", &singleton::get_x, &singleton::set_x)
    ;
}

及其用途:

>>> import example
>>> s1 = example.Singleton()
>>> s2 = example.Singleton()
>>> s1.x
0
>>> s2.x
0
>>> s1.x = 5
>>> s2.x
5

请注意,从Python的角度来看,这更类似于borg或单状态模式,因为它们共享状态,而不是身份。(即s1.x == s2.x,但id(s1) != id(s2)。)如果Python类也需要是一个单例,而不仅仅是它的状态,那么可能需要用Python代码而不是C++来实现这种行为。