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 {
void fire(const Request&, Response*) = 0;

class RPC {
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.

2 Replies to “Swig+Directors = Subclassing from Python!”

  1. Hi,
    This is a good example. I have a Doubt in SWIG only….
    Using SWIG can i make rpc calls??
    let us consider we are having add.c which resides at server side..
    and can we use that file in idl file to generate swig wrapper???

    1. Not directly; SWIG wouldn’t understand the IDL file itself.

      But you could generate a


      file from the IDL, and give that as input to SWIG. If you also wrapped the RPC client interface, then you could use Python or whatever language to make the RPC calls.

Leave a Reply

Your email address will not be published. Required fields are marked *