multiple callbacks ?

31 views
Skip to first unread message

Rémi Bèges

unread,
Jan 18, 2016, 12:21:10 PM1/18/16
to python-cffi
I have a pure-C library relying on a couple of function pointers stored inside a struct to abstract some hardware.

I would like to assign to each C function a specific python callback. I read the documentation, but I'm not sure this is doable. How can I achieve this ?

My struct with function pointers is the following :

struct TM_transport {
  int32_t (*read)(void * buf, uint32_t sizeToRead);
  int32_t (*readable)();
  int32_t (*write)(void * buf, uint32_t sizeToWrite);
  int32_t (*writeable)();
};


Please let me know if the question is not clear enough.


Armin Rigo

unread,
Jan 18, 2016, 12:32:27 PM1/18/16
to pytho...@googlegroups.com
Hi,

On Mon, Jan 18, 2016 at 6:21 PM, Rémi Bèges <remi....@gmail.com> wrote:
> I would like to assign to each C function a specific python callback. I read
> the documentation, but I'm not sure this is doable. How can I achieve this ?

You can generate a fixed number of callbacks:

ffi.cdef("""
extern "Python" int32_t my_read(void *, uint32_t);
extern "Python" int32_t my_readable(void);
etc.
""")

and then copy the function pointers "lib.my_read", "lib.my_readable",
etc. into your struct.

I'm not sure where the documentation fails to explain the above, or if
it doesn't answer your question. Feel free to expand if it does not.


A bientôt,

Armin.

Rémi Bèges

unread,
Jan 19, 2016, 5:45:59 AM1/19/16
to python-cffi, ar...@tunes.org
Hi Armin, thank you for the quick answer.

This is much clearer now.

What I find confusing in the documentation is the following sentence

The @ffi.def_extern() decorator should be applied to a global function, but only once. 

Yet it seems I can call def_extern for each of my python callbacks. That seems rather contradictory or am I missing something ? 

Regards

Armin Rigo

unread,
Jan 19, 2016, 10:12:29 AM1/19/16
to pytho...@googlegroups.com
Hi,

On Tue, Jan 19, 2016 at 11:45 AM, Rémi Bèges <remi....@gmail.com> wrote:
> The @ffi.def_extern() decorator should be applied to a global function, but
> only once.
>
> Yet it seems I can call def_extern for each of my python callbacks. That
> seems rather contradictory or am I missing something ?

Ah! Thanks for pointing it out, I'll fix the wording. What this
sentence means is that you should call @ffi.def_extern() only once
*for each C name;* i.e. you should avoid to call @ffi.def_extern()
many times, dynamically, to re-attach different Python functions
to a given C function. But it is expected that you call
@ffi.def_extern() 4 times if you have 4 different "extern Python" C
functions.


A bientôt,

Armin.
Reply all
Reply to author
Forward
0 new messages