Advanced C++ / Python integration with Boost.Python (Part 3)

In this final part of the series I’m going to look at one further way we can use Boost.Python to help when using a C++ class within Python.

In the previous part we built a wrapper for a C++ class, exposing a number of class methods to Python.

However, in Python, it’s quite typical for a class to use properties as well as methods.

So to begin – let’s take a moment to look at properties within the context of classes in Python.

For example, if we had a Python class which looks like this:

class simple:
    def __init__ (self):
        self._data = None

    def set_data(self, data):
        self._data = data

    def get_data(self):
        return self._data

We could then use it, something like this:

import example

s = example.simple()


Whilst this works, we might reasonably say that the necessity to use getter and setter functions directly is not especially Pythonic – as it’s not how most built-in objects behave.

Instead we’d expect to be able to use it more like this:

import example

s=example.simple() = 7


We can do exactly this; if we use properties…

Continue reading “Advanced C++ / Python integration with Boost.Python (Part 3)”

Advanced C++ / Python integration with Boost.Python (Part 2)

Last time we looked at how to use Boost.Python to wrap a very simple piece of C++ code. This time we’re going to take that one step further along, and do the same thing for a more complex C++ example – which includes a C++ Class.

For the purposes of this example – let us assume that we have a “legacy” C++ class (i.e. one that we’re not going to change): which looks something like this:

class ExampleClass

  void print_state();
  unsigned char* exporter();
  void set_data(uint8_t, uint8_t, uint8_t);
  void importer(unsigned char*, int);

  uint8_t a;
  uint8_t b;
  uint8_t c;


This (deliberately, slightly contrived) class has three methods (and a constructor). We can set the three 8-bit unsigned integers (uint8_t) directly using the set_data() method; we can print the data to the screen; or we can either import from or export to an unsigned char*.

In order to be able to use the importer & exporter methods with Python (via Boost.Python) we’ll need to further wrap these – as Boost.Python won’t let us use unsigned char* directly.

Continue reading “Advanced C++ / Python integration with Boost.Python (Part 2)”

Advanced C++ / Python integration with Boost.Python

In a previous post, I described how you could use the ctypes Python library to import a C++ class to make it usable from within Python. There is however, another way to do this; and that’s by using Boost.Python (which as the name suggests is a part of the Boost C++ library suite).

Whilst this method makes our code on the C++ side slightly more complicated; it significantly simplifies the Python code – and it let’s us use some more powerful features.

To begin let’s start with a simple example.

// hello.cpp

#include <boost/python.hpp>
#include <string>

char const* greet()
   return "hello, world";

std::string multi_bob(int n)
   std::string name = "Bob";
   std::string r = "";
   for (int i=0;i<n;i++)
      r += name;
   return r;

    using namespace boost::python;
    def("greet", greet);
    def("multibob", multi_bob);

Everything above the BOOST_PYTHON_MODULE line is perfectly ordinary C++ code. The clever bit comes in when we call the BOOST_PYTHON_MODULE macro (which is defined within the Boost.Python header)…

In this case we’re creating a Python module – with two methods: one based on our very simple greet() function (which we’re also going to call greet); and one based on the more complex multi_bob(int) function. Note that for this second function, to show the fact that the linkage between the C++ & Python code can be very flexible, we give it a different name on the Python side. Also note that we don’t need to tell the macro about the signature of the function as this is handled for us by Boost.Python.

Continue reading “Advanced C++ / Python integration with Boost.Python”

Tristate Multiplexing

Tristate multiplexing (or Charlieplexing) is a simple to use technique to expand the number of LEDs that you can light from a simple microcontroller. This post explores the concept, and looks at some interesting calculations we can do when thinking about them.

I’ve been meaning to get around to writing something of a tutorial on the basics of assembly programming using a PIC microcontroller for a while: and this post stared off as the first part of that… But then, in the best traditions of geekery, I got distracted by the interesting mathematics behind the scenes, and instead this post was born. But I’ve not given up on the idea and I will get back to that. Eventually. (But don’t hold your breath). Instead this post is written without any reference to any specific microcontroller architecture, and so you can use the ideas described here on a PIC, an Arduino, and it should even work on a Raspberry Pi (though I’ve not actually tried that yet).

To begin, let’s think about a simple situation where we have a microcontroller which we wish to use to control two LEDs. The simplest implementation is to use one of the microcontroller’s GPIO pins for each LED. This works well for a small number of LEDs; but very quickly gets expensive in terms of the number of pins it uses if you want more than a handful of LEDs; and depending on what else your microcontroller needs to do (and/or how many pins it has available to begin with) it soon becomes unsuitable.

The solution is to multiplex the LEDs – that is to say connect more than one LED to each pin, and use a combination of multiple pins to select the one we want.

Continue reading “Tristate Multiplexing”

Calling C++ Classes from Python, with ctypes…

I recently found myself needing to call a C++ class from within Python. I didn’t want to call a separate process (as I had previously when using Thrift – see Using Apache Thrift for Python & C++); but rather to call a C++ library directly.

Before I go on I should say that there are a lot of different ways to do this is Python – and I’ve picked one that worked for me. Other techniques are available – and opinion seems quite divided as to which (if any) technique is ‘best’.

To start with we have our C++ class, written in the usual way.

Continue reading “Calling C++ Classes from Python, with ctypes…”

Simple Python Hello World with Alexa

I’ve recently got myself an Amazon Echo Dot; Amazon’s speech-based, voice-controlled device using Amazon’s Alexa, digital assistant. They’re pretty nice devices; and they’re quite fun to play with (and not too expensive either) – though I’ve not had it long enough to say if it’s actually useful yet…

Obviously the first thing that I did with it was to try to write some code for it. (Actually that’s not quite true – the actual first thing that I did with it was to run through all of the many, funny and often very geeky, easter eggs that have been baked into the system. I think my personal favourite is “Alexa who is the mother of Dragons?” – closely followed by “Alexa: Tea. Earl Grey. Hot.”). But I digress…

Coding for Alexa is actually pretty easy; and appealingly for an old-school back-end programmer like me: there are no visual user-interfaces to worry about. It’s all done with simple JSON; in the form of a pretty simple web application. Perhaps more interestingly there’s no need to worry about the server for that application – since it’s ideally suited for using Amazon’s AWS Lambda Functions.

Continue reading “Simple Python Hello World with Alexa”

Using Apache Thrift for Python & C++

Apache Thrift is a software framework for cross-language: providing what is essentially a remote-procedure call interface to enable a client application to access services from a service — which can be written in the-same, or another language. Thrift supports all of the major languages that you’d expect to use: including Python, C++, Java, JavaScript / Node.js, and Ruby.

Unfortunately, whilst there are quite a few tutorials on how to use Thrift: some of them concentrate on explaining how Thrift is working behind the scenes (which is important, of course): rather than on how to use it. There also aren’t that many that concentrate on using C++. So having spent some time working through some of the tutorials (and the book Learning Apache Thrift), I though I’d have a go at writing something of a practical guide. I’m quite deliberately not going to focus on how Thrift works: if you want that, let me suggest the Apache Thrift – Quick Tutorial. I’m also going to assume that you have Thrift installed on your computer already (again, there are lots of sets of instruction on how to do this — Google will be your friend), and that you’re using a Linux or MacOS computer. You should be able to follow-along with most of this if you’re using Windows: but there will be a few differences, especially when it comes to compiling C++ files.

Continue reading “Using Apache Thrift for Python & C++”

RegEx Golf

RegEx Golf
Inspired by the famous XKCD cartoon that started it and by Google’s Peter Norvig over on O’ I decided to play some RegEx Golf myself this Easter…

If you’re not familiar with the game – the idea is to write the shortest regular expression possible that will select every element of a list, without selecting any elements from a second list. But what are regular expressions, you ask? Well, they’re a special sequence of characters that specify a particular textual patter – so you can use the appropriate regular expression when programming to automatically extract specific text from a list, file, or other text. There are some great tutorials on the web if you want to learn regular expressions (and you really should – because they’re great) – for example

I didn’t want to use lists of Presidents of the United States (as that had been done) – so I decided to have a go at the age-old challenge: animal, mineral, or vegetable

Continue reading “RegEx Golf”

Arduino I2C with the MCP9808 Temperature Sensor

The Microchip MCP9808 is a high precision temperature sensor with an I2C interface – making it easy to interface with microcontroller or embedded Linux electronics. The chip has a very small form-factor: available as either an 8-pin DFN package – or an 8-pin MSOP package. For hobbiest purposes DFN is almost impossible to use due to the complexity of having to reflow solder under the contacts; and MSOP is quite challenging (though it can be done with care). If you want something easy to use with a breadboard however, the good folks at Adafruit can come to the rescue – as they sell the device pre-soldered to a SIP breakout board. (Also available from Makersify in the UK).

Adafruit MCP9808 Breakout board
Adafruit MCP9808 Breakout board

If all you want to do is get something up and running quickly – then you can’t do better than to use the Adafruit Aurduino library (or if you prefer a Python library for BeagleBone or RPi).

Adafruit have done a great job with these libraries and most users will be delighted that “it just works”; but I want to explore how it all works: how to actually communicate with chip directly – using I2C. This guide written from the point of view of an Arduino; but you should be able to follow along from any other device if you’re reasonably familiar with I2C and low-level coding.

Continue reading “Arduino I2C with the MCP9808 Temperature Sensor”