computational science and engineering

Linking Python and C++ with Boost.python

Here is the “hello world” example from the Boost.python tutorial. I found that attempting to configure the Boost.jam build system is far more confusing than using GNU make to build the examples. The following presentation should be much easier to understand:

Save the following as hello_ext.C

[sourcecode language='c++']char const* greet()
{
return “hello, world”;
}

#include

BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def(“greet”, greet);
}
[/sourcecode]
Save the following as Makefile:

# location of the Python header files

PYTHON_VERSION = 2.6
PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)

# location of the Boost Python include files and library

BOOST_INC = /usr/include
BOOST_LIB = /usr/lib

# compile mesh classes
TARGET = hello_ext

$(TARGET).so: $(TARGET).o
	g++ -shared -Wl,--export-dynamic
	$(TARGET).o -L$(BOOST_LIB) -lboost_python
	-L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION)
	-o $(TARGET).so

$(TARGET).o: $(TARGET).C
	g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).C

Save the following as test_hello.py
[sourcecode language='python']import hello_ext
print hello_ext.greet()[/sourcecode]
That’s it.