当库成功加载时,通用的模式是将其存储为与库名称相同的模块级变量。函数可以作为对
象属性访问,因此调用它们就像调用从任何其他导入模块导入的Python 函数一样,如下所示:
import ctypes
from ctypes.util import find_librarylibc = ctypes.cdll.LoadLibrary(find_library(‘c’))
libc.printf(b"Hello world!\n")
Hello world!
13
不幸的是,除了整数,字符串和字节之外的所有内置Python 类型都与C 数据类型不兼
容,因此必须使用ctypes 模块提供的相应类进行包装。表7-1 是来自ctypes 文档的兼
容数据类型的完整列表。
表7-1
ctypes 类型 C 类型 Python 类型
c_bool _Bool bool (1)
c_char char 单字符bytes 对象
ctypes 类型 C 类型 Python 类型
c_wchar wchar_t 单字符string
c_byte char int
c_ubyte unsigned char int
c_short short int
c_ushort unsigned short int
c_int int int
c_uint unsigned int int
c_long Long int
c_ulong unsigned long int
c_longlong __int64 or long long int
c_ulonglong unsigned __int64 or unsigned long long int
c_size_t size_t int
c_ssize_t ssize_t or Py_ssize_t int
c_float float float
c_double double float
c_longdouble long double float
c_char_p char * (NUL terminated) bytes 对象 或 None
c_wchar_p wchar_t * (NUL terminated) string 或 None
c_void_p void * int 或 None
如你所见,上表不包含任何将Python 集合映射成C 数组的专用类型。为C 数组创建
类型的推荐方法是简单地使用带有所需基本ctypes 类型的乘法运算符,如下所示:
import ctypes
IntArray5 = ctypes.c_int * 5
c_int_array = IntArray5(1, 2, 3, 4, 5)
FloatArray2 = ctypes.c_float * 2
c_float_array = FloatArray2(0, 3.14)
c_float_array[1]
3.140000104904175