Python Programming/Extending with ctypes

From Wikibooks, open books for an open world
Jump to: navigation, search

ctypes[1] is a foreign function interface module for Python (included with Python 2.5 and above), which allows you to load in dynamic libraries and call C functions. This is not technically extending Python, but it serves one of the primary reasons for extending Python: to interface with external C code.

Basics[edit]

A library is loaded using the ctypes.CDLL function. After you load the library, the functions inside the library are already usable as regular Python calls. For example, if we wanted to forego the standard Python print statement and use the standard C library function, printf, you would use this:

from ctypes import *
libName = 'libc.so' # If you're on a UNIX-based system
libName = 'msvcrt.dll' # If you're on Windows
libc = CDLL(libName)
libc.printf("Hello, World!\n")

Of course, you must use the libName line that matches your operating system, and delete the other. If all goes well, you should see the infamous Hello World string at your console.

Getting Return Values[edit]

ctypes assumes, by default, that any given function's return type is a signed integer of native size. Sometimes you don't want the function to return anything, and other times, you want the function to return other types. Every ctypes function has an attribute called restype. When you assign a ctypes class to restype, it automatically casts the function's return value to that type.

Common Types[edit]

ctypes name C type Python type Notes
None void None the None object
c_bool C99 _Bool bool
c_byte signed char int
c_char signed char str length of one
c_char_p char * str
c_double double float
c_float float float
c_int signed int int
c_long signed long long
c_longlong signed long long long
c_short signed short long
c_ubyte unsigned char int
c_uint unsigned int int
c_ulong unsigned long long
c_ulonglong unsigned long long long
c_ushort unsigned short int
c_void_p void * int
c_wchar wchar_t unicode length of one
c_wchar_p wchar_t * unicode