ctypes callback with char array

Diez B. Roggisch deets at web.de
Sat Jun 2 06:52:04 EDT 2012


ohlfsen <ohlfsen at gmail.com> writes:

> Hello.
>
> Hoping that someone can shed some light on a tiny challenge of mine.
>
> Through ctypes I'm calling a c DLL which requires me to implement a callback in Python/ctypes.
>
> The signature of the callback is something like
>
> void foo(int NoOfElements, char Elements[][100])
>
> How do I possible implement/process "char Elements[][100]" in Python/ctypes code?

I'd try it like this:

$ python
Python 2.7 (r27:82500, May  2 2011, 22:50:11) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
oWelcome to rlcompleter2 0.98
for nice experiences hit <tab> multiple times
>>> from ctypes import *
>>> callback_type = CFUNCTYPE(None, c_int, POINTER(c_char_p))
>>> def my_callback(int, elements):
...     pass
... 
>>> c_callback = callback_type(my_callback)
>>> c_callback
<CFunctionType object at 0x100697940>


No need to know that it's a pointer to char[100] pointers - you can cast
that if you want to.

Diez



More information about the Python-list mailing list