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.

Swig+Directors = Subclassing from Python!

2 thoughts on “Swig+Directors = Subclassing from Python!

  1. Kaushik says:

    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. power says:

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

      But you could generate a .h 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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s