Test codes and pipeline
foo.cpp
:
#include <boost/python.hpp>
#include <iostream>
namespace bp = boost::python;
using namespace std;
class Foo
{
public:
Foo(int n) {
cout << "in Foo::Foo()" << endl;
value = n;
}
void set(int n) { value = n; }
int get() { return value; }
private:
int value;
};
BOOST_PYTHON_MODULE(foo){
bp::class_<Foo>("Foo", bp::init<int>())
.def("get", &Foo::get)
.def("set", &Foo::set);
}
Makefile
:
CPPFLAGS = -I/usr/include/python2.7
CXXFLAGS = -Wall
LDFLAGS = -fPIC -shared
LDLIBS = -lboost_python -lpython2.7
foo.so: foo.cpp
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $^ $(LDLIBS) -o $@
.PHONY: clean
clean:
rm -f foo.so *.o
test in python:
>>> from foo import Foo
>>> BP = Foo.__base__ # Boost.Python.instance
>>> @staticmethod
>def _Foo_new(cls, *args, **kwargs):
> print cls
> print 'args:', args
> print 'kwargs:', kwargs
> return BP.__new__(cls, *args, **kwargs)
>>> Foo.__new__ = _Foo_new
>>> f = Foo(23)
<class 'foo.Foo'>
args: (23,)
kwargs: {}
in Foo::Foo()
>>> # "f = F(23)" is equivalent to
>>> f = Foo.__new__(Foo)
>>> f.__init__(23)
>>> f.get()
23
Inheritance tree
Conclusion
Boost.Python
- wrap instance of C++ class in the wrapper
- calling order in python:
__new__
__init__
- create C++ instance
- initialize C++ instance