[Tutor] c struct with python

Alan Gauld alan.gauld@blueyonder.co.uk
Sat May 31 17:28:01 2003


> I have a c structure which i am representing with a class in python.
The
> structure is of the form:
>
> typedef struct abc
> {
>     void (*XY)(int a, int b);
> }ABC;
>
> void XY(int a, int b)
> {...}

> Can someone tell me how this can be handled in python.

You have a structure containing a pointer to a function
that takes two (integer) arguments and no return value.

A similar function in python is easy:

def XY(a,b): pass

And you can put that in any Python structure you want,
including a class:

class ABC:
   def __init__(self, func):
     self.XY = func

NOw you can instantiate ABC:

abc = ABC(XY)

and call the function like:

abc.XY(3,4)

Or you could store it in a tuple, or a list or a dictionary.

funcList = [XY]
funcTuple = (XY)
funcDict = {'XY':XY}

And call them like so:

funcList[0](3,4)
funcTuple[0](3,4)
funcDict['XY'](3,4)

Does that help?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld