4 ms·
You have several options for calling C functions directly from Python without having to start a separate process and communicate with it. For simple jobs when y
by pkkm 3y ago
You have several options for calling C functions directly from Python without having to start a separate process and communicate with it. For simple jobs when you just want to call a function or two, ctypes from the standard library is a great choice. You load a dynamic library, define the argument and return types of the function you want to call, and call it. It can even handle callbacks from C code into Python.
When you have a lot of C functions to call, having to duplicate all the declarations in Python code gets old. That's where the third-party cffi module comes in. It can parse straightforward C headers and use the appropriate types automatically. However, for complex headers (lots of macros, for example), it has to run a C compiler, which requires the machine which will run the script to have a functioning C toolchain. When using cffi, it can also be pretty easy to crash the interpreter with a use-after-free bug.
If you're already invested in the Cython ecosystem, you can use that for calling into C too. However, getting into Cython just to call a few C functions would be cracking a nut with a sledgehammer.
Finally, the nuclear option is to write a C extension module. Extension modules receive unconverted Python objects directly and can deeply integrate with the CPython interpreter. However, they also need to be compiled for a specific version of CPython, and won't necessarily work in alternative Python implementations. If you can get the job done with ctypes or cffi, you should avoid extension modules.