Bridging Python and C & Introduction to ctypes

Bridging Python and C & Introduction to ctypes

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).


Slide 6

So we’re not going to talk about SWIG, SIP, Shiboken, etc. Just Python and C.

Slide 9

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.

Slide 12

Suitable if: You need to write some C anyway, and is knowledgable enough with CPython internals.

Slide 13

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.

Slide 17

You can see how similar ctypes code is to straight C.

Slide 21

Also there are some types from stdint.h and others, e.g. c_int32 (mapped to int32_t). The naming rules are pretty straightforward.

Slide 23

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.
int declaration.

Slide 24

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).

Slide 30

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.

Slide 35

Remember, unions and structures are all Python classes, and can have normal Python attributes! Use them!

Slide 41

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.


Tzu-ping Chung

June 25, 2015