How to return a function pointer from CPython in Python, then call a C function using ctypes?

I have a CPython function:

void my_cfunc(int arg)
{
  printf("Hello from C; arg=%d\n", arg);
}

PyObject *get_fptr(PyObject * /*self*/, PyObject * /*args*/)
{
    return PyCObject_FromVoidPtr(my_cfunc, NULL);
}

Then in Python I have:

import mymodule

ptr = mymodule.get_fptr() # will return a PyCObject wrapping the C function pointer

Then later:

from ctypes import *

SOMEFUNC_T = CFUNCTYPE(c_void, c_int)
somefunc = SOMEFUNC_T(ptr) # <-- bad!

Now, if I change get_fptr to return as: PyLong_FromSize_t (size_t (my_cfunc)), then "somefunc" will execute.

But I do not want to use a pointer to the size_t function.

Please inform

+3
source share
1 answer

First of all, I don’t understand why you want to return the C function pointer from the Python extension only to call it from Python (via ctypes), while the logical task would be to call the C function through the Python extension (if I am missing something )

-, , ctypes PyCObject. CFUNCTYPE (None, c_int) [ c_void None] PyCObject, CFUNCTYPE , PyCObject.

Python my_cfunc, Python ctypes? :

PyObject *call_fptr(PyObject *self, PyObject *args)
{
    int arg;
    if (!PyArg_ParseTuple(args, "i", &arg))
        return NULL;

    my_cfunc(arg);
    Py_RETURN_NONE;
}

, ctypes - , Python my_func ctypes ( PyCObject)!

from ctypes import *
import foo

SOMEFUNC_T = CFUNCTYPE(None, c_int)
cfunc = SOMEFUNC_T(foo.call_fptr)
cfunc(1)

Edit: , C , ... C ctypes, , CFUNCTYPE ?

Python C, , , , . SWIG , , , : , .

, , libffi.

, , , SWIG .

+1

Source: https://habr.com/ru/post/1795570/


All Articles