How to pass a function pointer to a C api in Python 3.8

Viewed 22

I have a C API with a error message callback:

extern void set_errcb(void (*errcb)(const char *));

It is exposed to python with the python function:

module.set_errcb(errcb)

How do I pass a function pointer argument in python?

I tried this:

import module

def my_errcb(msg):
    print(msg)

module.set_errcb(errcb)

and I get this error:

TypeError: in method 'set_errcb', argument 1 of type 'void (*)(char const *)'

How to pass my callback to C? Can I do this? How else should I handle this case if this isn't possible?

Edit: I found I could do something like this:

from ctypes import *

msgfunc = CFUNCTYPE(c_char_p)
module.set_errcb(msgfunc(errcb))

But I still get the same error as above:

TypeError: in method 'args_set_errcb', argument 1 of type 'void (*)(char const *)'
0 Answers
Related