How to return a function pointer from CPython to Python then call a C function with ctypes? -
i have cpython function:
void my_cfunc(int arg) { printf("hello c; arg=%d\n", arg); } pyobject *get_fptr(pyobject * /*self*/, pyobject * /*args*/) { return pycobject_fromvoidptr(my_cfunc, null); }
then later, in python have:
import mymodule ptr = mymodule.get_fptr() # return pycobject wrapping c function pointer
then later:
from ctypes import * somefunc_t = cfunctype(c_void, c_int) somefunc = somefunc_t(ptr) # <-- bad!
now, if change get_fptr return as: pylong_fromsize_t(size_t(my_cfunc)) 'somefunc' valid.
but don't want cast function pointer size_t.
please advise
first of all, don't understand why you'd want return c function pointer python extension call python (via ctypes), while logical thing call c function via python extension (unless i'm missing something).
second, not ctypes supports pycobject @ all. call cfunctype(none, c_int) [i replaced c_void none] pycobject argument fails because cfunctype expects integer, , not know pycobject.
why not write python wrapper my_cfunc instead, you'll call python without ctypes hassle? example:
pyobject *call_fptr(pyobject *self, pyobject *args) { int arg; if (!pyarg_parsetuple(args, "i", &arg)) return null; my_cfunc(arg); py_return_none; }
as bonus, if ctypes thing, python wrapper my_func can used instantiate ctypes foreign function (unlike pycobject)!
from ctypes import * import foo somefunc_t = cfunctype(none, c_int) cfunc = somefunc_t(foo.call_fptr) cfunc(1)
edit: specifying c function should take variable number of arguments makes question more difficult... how wrap variable argument c function ctypes anyway, considering cfunctype requires known set of arguments?
the problem in case boils down converting python tuple variable argument list in c, apparently trivial. in fact swig has dedicated section of documentation problem, saying instance this: most other wrapper generation tools have wisely chosen avoid issue.
it give advise, though, 1 can dynamically construct variable argument lists in portable manner of libffi.
my suggestion, ultimately, wrap variable arguments function swig , save pain.
Comments
Post a Comment