None

Basic Python ctypes

December 9, 2009

The easiest way to call C from Python seems to be ctypes.

Simple Example on Windows

>>> import ctypes
>>> libc = ctypes.CDLL("msvcrt")
>>> print libc.strlen("Hello!")
6
>>> libc.printf("Argument");
Argument8
>>> num_bytes = libc.printf("the number %d and string %s\n", 10, "spam")
the number 10 and string spam
>>> print num_bytes
30
>>> value = libc.printf("Hello World!\n");
Hello World!
>>> libc.printf("Hello World!");
Hello World!12

the printf example above that don't assign the result - the python interpreter is doing the printf, then printing out the return value of the function, which is the number of bytes printed. Hence the 12 following Hello World!

Unix

importing the original library works using the following code on Solaris:

>>> libc = ctypes.CDLL("libc.so")

This code does, however, give invalid ELF header on Fedora 11. This works though:

>>> libc = ctypes.CDLL("libc.so.6")

Links