Here is the example program:
#include <iostream>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
void helloWorld() {
std::cout << "Hello World!\n";
}
int add(int a, int b) {
return a + b;
}
BOOST_PYTHON_MODULE(libhello) {
using namespace boost::python;
def("hello", helloWorld);
def("add", add);
}
To compile this into a shared library, first you need to compile the object file and then make a shared object out of it:
g++ -I/usr/include/python2.7 -fPIC -c -o hello.o pythonWorld.cpp g++ -fPIC -shared -Wl,-soname,"libhello.so" -o libhello.so hello.o -lboost_python
-Wl: Pass option as an option to the GNU linker. If option contains commas, it is split into multiple options at the commas (taken from http://tigcc.ticalc.org/doc/comopts.html).
Now you can import the module libhello in python and call its functions (given it is in a place where python can find it).
This was my first very simple program to get a touch on boost python. If there are mistakes in what I did that just did not have any effect because of simplicity and might show up in more complex programs, I will be very thankful if you point it out.