Quantcast
Viewing all articles
Browse latest Browse all 19

Swig+Directors = Subclassing from Python!

Swig is a fabulous tool — I generally rely on it to extricate myself from the holes I’ve managed to dig myself into using C++.  Swig parses C++ code and generates wrappers for a whole bunch of target languages — I normally use it to build Python interfaces to my C++ code.

A cool feature that I’ve never made use of before is “directors” — these let you write subclasses for your C++ code in Python/(whatever language use desire).  In particular, this provides a relatively easy mechanism for writing callbacks using Python.  Here’s a quick example:

// rpc.h
class RPCHandler {
public:
void fire(const Request&, Response*) = 0;
}

class RPC {
public:
void register_handler(const std::string& name, RPCHandler*);
};

Normally, I’d make a subclass of RPCHandler in C++ and register it with my RPC server. But with SWIG, I can actually write this using Python:

class MyHandler(wrap.RPCHandler):
  def fire(req, resp):
    resp.write('Hello world!')

It’s relatively straightforward to setup. I write an interface file describing my application:

// wrap.swig
// Our output module will be called 'wrap'; enable director support.
%module(directors="1") wrap
%feature("director") RPCHandler;

// Generate wrappers for our RPC code
%include "rpc.h"

// When compiling the wrapper code, include our original header.
%{
#include "rpc.h"
%}

That’s it! Now we can run swig: swig -c++ -python -O -o wrap.cc wrap.swig

Swig will generate wrap.cc (which we compile and link into our application), and a wrap.py file, which we can use from Python.


Viewing all articles
Browse latest Browse all 19

Trending Articles