擅长:python、mysql、java
<p>抽象类实际上可以在没有包装器的情况下公开给Boost.Python。
诀窍是用<em>boost::noncopyable</em>定义类,并避免使用<em>纯虚拟</em>方法包装器。</p>
<p>下面是正确的代码(使用Boost.Python 1.47.0和Python 2.7.6进行了测试):</p>
<pre><code>#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/module.hpp>
struct Base
{
virtual int foo() = 0;
};
struct Derived : public Base
{
virtual int foo()
{
return 42;
}
};
Base* get_base()
{
return new Derived;
}
BOOST_PYTHON_MODULE(libTestMod)
{
namespace py = boost::python;
py::class_<Base, boost::noncopyable>("Base", py::no_init)
.def("foo", &Base::foo);
py::def("get_base", get_base,
py::return_value_policy<py::reference_existing_object>()); //ignore mem leak
}
</code></pre>
<p>测试:</p>
<pre><code>$ python
Python 2.7.6 (default, Mar 31 2014, 16:04:58)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import libTestMod
>>> base = libTestMod.get_base()
>>> print base.foo()
42
</code></pre>