[OT] pass a C callback function to a cythom module via python

Nadav Horesh nadavh.horesh at gmail.com
Fri Mar 16 01:42:57 EDT 2012


I have the following:

   - A library of C function which is compiled into a dll
   - A cython module with a function that expects as a parameter a C
   callback function.

My problem is how to make a python script to pass directly the address of a
C function from the dll to the cython function.

example:

-- C code ---

float mul(float a, float b)

{

  return a*b;

}


-- cython module --

ctypedef float c2f(float, float)

def call_c(c2f fun, float x, float y):
    return fun(x, y)

----------------------

I can use ctypes as the follows, but the call goes through a python wrapper

from ctypes import *

import cython_module

dll = cdll.LoadLibrary('./C_modile.so')

mul = dll.mul

mul.argtypes = [c_float, c_float]
mul.restype = c_float

cython_module.call_c(mul, c_float(3), c_float(2))


I found a work around by adding the following line to the C code:


void* mulp = mul


So the following line in the python module provides the address of the mul
function:


mull_addr = c_void_p.in_dll(dll, "mul")


I am wondering if there is a friendly and simple(r)  solution.


   Nadav.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/scikit-image/attachments/20120316/7f429d57/attachment.html>


More information about the scikit-image mailing list