Help with implementing callback functions using ctypes

jamadagni samjnaa at gmail.com
Thu May 23 23:11:40 EDT 2013


On Friday, May 10, 2013 12:02:08 AM UTC+5:30, Nobody wrote:
> This line should be:
>   spiro_to_bezier_strict ( src, len ( src ), byref(bc) )
> Without the byref(...), it will try to pass a copy of the structure rather
> than passing a pointer to it.

Wow silly silly mistake of mine, passing an object where a pointer is expected. Alternatively, if I specify:

spro_to_bezier_strict.argtypes = [ POINTER(spiro_cp), c_int, POINTER(bezctx) ]

it works equally good and apparently automatically converts the object specified to a pointer to it (which is good and intuitive, I guess, though against C practice).

I guess if one wants to be safe when interfacing to C functions, one should always specify argtypes (even if not restype).

But really, a segfault? I would expect a more meaningful error or an exception to be raised. Or is the black magic occurring at a level lower than where Python's control goes?

If I had seen this post I might not have even spent time on Cython. (For some reason Google Groups doesn't send me email updates even if I ask it to.) Using CTYpes I was able to implement a callback with less coding (for this particular requirement) than Cython which required an extra wrapper layer on top of the library to pass through a void* representing the Python callback (or a state variable would have to be used which may mean no thread-safety).

But I guess Cython would be faster for those who want that. Even though there is an extra function call every time (for the wrapper) it would be faster since it's at the C level rather than at the Python level (or something like that).

Thanks to all who helped on this, and also the people over at the cython-users list who helped me on the Cython wrapper too.



More information about the Python-list mailing list