[Pyrex] Function pointer question

Lenard Lindstrom len-l at telus.net
Sun Dec 4 22:34:28 CET 2005


On 3 Dec 2005 at 14:02, vanitha at cs.wisc.edu wrote:

> Hi All:
> I have a function in C that takes a function pointer as the argument, but
> the function that is being passed in is implemented in Python. Can I use
> Pyrex to wrap this C function? How do I pass the Python function in as a
> function pointer to the C Function? A example will be greatly appreciated.
> 

The only way I know of is to first assign the Python function to a 
python global then call it from a C callback.

============= callback.pyx ==================
# A C function that takes a callback
cdef void SomeCFunction(void (*cfn)(int x)):
    cfn(42)

# Python Wrapper
cdef object callback_ref  # Python callback function

cdef void CCallbackFunction(int x):
    callback_ref(x)

def SomeFunction(fn):
    """Call Python function fn from SomeCFunction"""
    global callback_ref
    callback_ref = fn
    SomeCFunction(CCallbackFunction)
============= setup.py ======================
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext

setup(
  name = 'callback',
  ext_modules=[ 
    Extension("callback",       ["callback.pyx"]),
    ],
  cmdclass = {'build_ext': build_ext}
)
============= interactive session ==============
>>> import callback
>>> def foo(i):
...     print i
...
>>> callback.SomeFunction(foo)
42

Lenard Lindstrom
<len-l at telus.net>




More information about the Pyrex mailing list