SWIG and Python help needed

Chris Gonnerman chris.gonnerman at newcenturycomputers.net
Sat Jan 18 16:43:55 CET 2003

I'm working on a rewrite of the gdmodule code (which I now
maintain) using SWIG for the low-level module and Python
for the upper level... and I have hit a wall.

The GD library supports reading and writing most image formats
using a gdIOCtx structure.  It contains pointers to functions
for reading, writing, seeking, etc.  I'd like to be able to
use any Python object implementing the "file" interface with
gdmodule (rather than only the "traditional" FILE * -based 
internal file objects), and this I/O interface seems like the
way to go.

I can't figure out how to get there from here.  I have inspected
the .c file produced by SWIG, and created the following function:

static PyObject *gdXNewIOCtx(PyObject *self, PyObject *args) {
    PyObject *resultobj;
    PyObject *arg0 ;
    XgdIOCtx *result ;

    if(!PyArg_ParseTuple(args,(char *)"O:gdXNewIOCtx",&arg0)) return NULL;

    result = (XgdIOCtx *)malloc(sizeof(XgdIOCtx));

    if(result == NULL)
        return NULL;

    result->py = arg0;
    result->io.getC = gdXgetC;
    result->io.getBuf = gdXgetBuf;
    result->io.putC = gdXputC;
    result->io.putBuf = gdXputBuf;
    result->io.seek = gdXseek;
    result->io.tell = gdXtell;
    result->io.gd_free = gdXgd_free;

    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_gdIOCtx);
    return resultobj;

This should create an object compatible with the standard
SWIG wrapper for the "gdIOCtx *" type.  The XgdIOCtx structure
is just this:

typedef struct {
    gdIOCtx io;
    PyObject *py;
} XgdIOCtx;

which I have defined in the .i file in the header section
(since I don't want SWIG to wrap it).  The functions inserted
into the io structure will handle calling back into Python,
using the python-object pointer "py".

How do I get this inserted into the method array?  Or am I
barking up the wrong tree?

Any help would be appreciated.

Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net

More information about the Python-list mailing list