function pointers

Jeff Epler jepler at unpythonic.net
Mon Jun 2 12:23:20 EDT 2003


On Mon, Jun 02, 2003 at 09:17:20PM +0530, Jimmy verma wrote:
> Hello !
> 
> I have a few statements in C for which i want to write the equivalent code 
> in python:
> 
> typedef int (*AB)(int a, int b);          #a function pointer type used to 
> describe signature of some function.

No static typing in Python.  You might want to be aware of the built-in
function callable(), though.  It returns True if the argument is
callable (function, method, or class-with-__call__).  Just like in C,
you can "assign the function pointer" with the regular assignment
operator.  For instance,
    x = max
    print x(1, 2, 3) #-> prints 3
    x = min
    print x(1, 2, 3) #-> prints 1

> Then a structure of the form
> 
> typedef struct abc
> {
>       AB make;
>       int a;
> }ABC;

class ABC:
    def __init__(self, make, a):
        self.Make = make
        self.a = a

> 
> Now this structure is getting passed to some function
> 
> xyz(const ABC* inter)
> {
>         #some code here
>          e = inter->Make(a, b);
> }

(I'm guessing that 'a' is actually inter->a)
def xyz(inter):
    # some code here
    e = inter.Make(inter.a, b)

It may make sense for xyz to be a method of ABC, or it may not.  If it
were, then you'd write it together with the 'class' definition:

class ABC:
    def __init__(self, make, a):
        self.Make = make

    def xyz(self):
        # some code here
        e = self.Make(inter.a, b)

Jeff





More information about the Python-list mailing list