function pointers

W Isaac Carroll icarroll at pobox.com
Mon Jun 2 12:27:50 EDT 2003


Jimmy verma wrote:
> Hello !

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.

Because Python is dynamically typed, you don't declare types or 
signatures. Once a function is defined, just use its name like you would 
a pointer. You can assign it to another variable or pass it to another 
function.

     def func(arg1, arg2):
         # function body

     othervar = func
     otherfunc(func)

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

This is usually written:

     class ABC:
         pass

     cba = ABC()
     cba.make = func
     cba.a = 42

If you really want to enforce which fields are allowed, you can use 
"slots", but don't do that until you know the Pythonic reasons for it.

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

Functions are treated just like other data types in Python.

     def xyz(inter):
         # some code here
         e = inter.make(a, b)   # case is significant just like in C

> How can i handle it with python.

I hope this has helped your exploration of Python.

TTFN






More information about the Python-list mailing list