ctypes — A foreign function library for Python

 Ctypes is a foreign function library in Python designed for interoperability with C. It facilitates the usage of C-compatible data types and enables the invocation of functions from dynamic link libraries (DLLs) or shared libraries. Additionally, ctypes provides a mechanism to encapsulate and utilize these libraries directly within pure Python code.


Ctypes Tutorial

The code samples in this tutorial utilize doctest to ensure their functionality across different platforms, such as Linux, Windows, or macOS. Due to potential variations in behavior on different platforms, the code contains doctest directives within comments.


Please note that certain code samples make reference to the ctypes.c_int type. On platforms where the size of long is the same as the size of int, ctypes.c_int is an alias to ctypes.c_long. Consequently, if c_long is printed instead of c_int, it should not cause confusion, as they are, in fact, the same type.


Loading Dynamic Link Libraries

Ctypes provides objects such as cdll, and on Windows, windll and oledll, for loading dynamic link libraries.


Libraries are loaded by accessing them as attributes of these objects. Specifically, cdll is used for libraries exporting functions with the standard cdecl calling convention. On the other hand, windll is suitable for libraries that call functions using the stdcall calling convention. Additionally, oledll assumes the stdcall calling convention and expects functions to return a Windows HRESULT error code. This error code is employed to automatically raise an OSError exception when a function call encounters a failure.

Post a Comment

Previous Post Next Post