Shadows In Rain
Shadows In Rain

Reputation: 1220

Cython + ctypes?

We are currently using Cython to make bindings to some networking and DB libraries. We want also use SDL, but PySDL2 uses ctypes for binding. While Cython is whole interpreter, ctypes is just library. But, Cython and ctypes are most often portrayed as alternatives to each other. Thus I am totally unsure if they are compatible.

So, question: it is possible to use Cython and ctypes together in one project?

Upvotes: 3

Views: 3143

Answers (1)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

Here's a brief summary of how both tools work:

ctypes is a very pythonic wrapper over a library called cffi, which is able to load shared libraries (.so or .dll files), and call them, without first compiling any code to wrap the functions defined in those libraries. You do have to tell ctypes about the functions it'll call, so that it can convert from the python types (int, str, and so on) to the abi expressed in the shared lib (uint32_t, char *, and so on).

Cython is a 'sort of python' to C translator. The generated C code can be compiled and the result is a special sort of shared library (.so or .dll again) which has all the right functions to be a Python C extension. Cython is very smart, based on the type annotations in the input, it knows whether to emit code that directly calls C functions (when you use cdef) or calls regular python objects by way of the PyObject_Call C api.

Since you can (more or less) freely mix C and python in Cython sources, you should have no difficulty using PySDL2 in your Cython library, just invoking it as though it were regular python, import it, call it, everything should "just work".

That said, You might benefit from including libsdl declarations in your code, directly, if you end up calling out to SDL from tight inner loops, to avoid the overhead of converting from the low level C types to python types, just to have ctypes convert them back again. You could probably put that off until your application has grown a bit and you notice some performance bottlenecks.

Upvotes: 5

Related Questions