Saturday, January 5, 2013

boost python

Boost Python is a very helpful tool if you want to access fast C++ code in Python. For the longest time I have avoided starting to use it, because it seemed rather confusing to me. Now I had a look at a Hello World! example and it doesn't seem that hard to me anymore (of course, complexity comes with more advanced modules).

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.

Thursday, January 3, 2013

Raspberry Pi cross-compiler

If you have a raspberry pi, you might want to build your own cross-compiler, because compiling on the pi is not very fast and if you have a template heavy library, compiling might exceed the pi's memory capacities. As that happened to me, I decided to build a toolchain using crosstools-ng on linux mint 12.
I stuck to these instructions that I found on google. However, whatever combination of gcc, target linux kernel and binutils version I chose, building the chain failed when building binutils.
I tried to build binutils on my and even then it failed. So I got rather frustrated, but after some search on the web, I came across a solution. It's as simple as that:
If your C_INCLUDE_PATH ends with a trailing colon, just remove that colon. After doing that I did not have any trouble compiling binutils, both on my own as well as part of the toolchain.

More detailed instructinos can be found on this blog.
I tested the toolchain and I was able to compile Hello World for my raspberry pi. So now is the time to have a look at more sophisticated stuff.