Some solutions to work with C code/library in Python, and introduction to ctypes, a pure-Python solution to make use of compiled C shared objects. Also some tips and tricks when working with ctypes (and C in general).
So we’re not going to talk about SWIG, SIP, Shiboken, etc. Just Python and C.
First: You don’t have the code (yet).
Second: You have the code, but you need to compile it.
Third: You have a compiled binary, and you want to use it in Python.
Suitable if: You need to write some C anyway, and is knowledgable enough with CPython internals.
Suitable if: You’re dealing with very little or non existing C code. Writing Cython is a lot easier than C, so you get speed in the binding with much hassle.
You can see how similar ctypes code is to straight C.
Also there are some types from stdint.h and others, e.g. c_int32 (mapped to int32_t). The naming rules are pretty straightforward.
Another example. (Python equivalent in the next slide.)
Notice three topics:
void * and non-NULL-terminated char * printing.
int * “out” parameter, pass by pointer, and address-of (&) operator.
Rough Python equivalent of the previous C code. Look at how each set of syntaxes is translated.
Note: C type variables are always initialised in ctypes, even if you don’t pass a value! c_int() is equivalent to c_int(0).
This is “Hello World” with ctypes. The point here is, function annotations are just hints, and are optional.
They are recommended, but you should use them as a tool, not an obligation.
Slide 31 & 32
You might get into trouble if you follow the C declaration blindly. Remember, C is weakly-typed.
Remember, unions and structures are all Python classes, and can have normal Python attributes! Use them!
This last one helps me very often. I find it extremely helpful to write some simple C programs first, then translate them into Python with ctypes.