boost python wrap c类私有成员
作者:互联网
我们可以用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 instance\n";
}
friend Singleton* create();
};
Singleton* pInstance_;
Singleton* create()
{
if(!pInstance_)
{
pInstance_ = new Singleton();
}
else
{
cout << "Using old instance\n";
}
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
标签:boost-python,python,c,boost 来源: https://codeday.me/bug/20190831/1776878.html