4 ms·
How do you call C API from python? Through executable + stdin/stdout?
by zeusk 3y ago
How do you call C API from python? Through executable + stdin/stdout?
- hprotagonist 3y agohttps://pypi.org/project/cffi/ https://pypi.org/project/cffi/
- formerly_proven 3y agohttps://docs.python.org/3/library/ctypes.html https://docs.python.org/3/library/ctypes.html
- LtWorf 3y agoYep this is how I did it. Using a subprocess and pipes wouldn't work with a .so file. I'd need to write a C wrapper to implement a way to call functions and marshall parameters in binary… Basically CORBA over a pipe rather than a socket!
- hermitdev 3y agoCPython is written in C, and has an extensive API, also in C. A good number of CPython's stdlib is implemented in C. It's fairly easily to write an extension lib in C or C++ or Rust, even, and have python dynamically load the library. Shared libs have to be linked differently than they normally are as ld.so needs to be able to locate and load any dependencies. Libs are typically referred to as 'dlo's instead of 'so's to make the distinction.
- pkkm 3y agoYou 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.