Python Programming/Extending with ctypes
ctypes 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.
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 ValuesEdit
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.
|ctypes name||C type||Python type||Notes|
|None||void||None||the None object|
|c_char||signed char||str||length of one|
|c_longlong||signed long long||long|
|c_ulonglong||unsigned long long||long|
|c_wchar||wchar_t||unicode||length of one|