## 问题
You have a small number of C functions that have been compiled into a shared libraryor DLL. You would like to call these functions purely from Python without having towrite additional C code or using a third-party extension tool.
## 解决方案
For small problems involving C code, it is often easy enough to use the ctypes modulethat is part of Python’s standard library. In order to use ctypes, you must first makesure the C code you want to access has been compiled into a shared library that iscompatible with the Python interpreter (e.g., same architecture, word size, compiler,etc.). For the purposes of this recipe, assume that a shared library, libsample.so, hasbeen created and that it contains nothing more than the code shown in the chapterintroduction. Further assume that the libsample.so file has been placed in the samedirectory as the sample.py file shown next.To access the resulting library, you make a Python module that wraps around it, suchas the following:# sample.pyimport ctypesimport os
# Try to locate the .so file in the same directory as this file_file = ‘libsample.so'_path = os.path.join([*](#)(os.path.split(__file__)[:-1] + (_file,)))_mod = ctypes.cdll.LoadLibrary(_path)
# int gcd(int, int)gcd = _mod.gcdgcd.argtypes = (ctypes.c_int, ctypes.c_int)gcd.restype = ctypes.c_int
# int in_mandel(double, double, int)in_mandel = _mod.in_mandelin_mandel.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_int)in_mandel.restype = ctypes.c_int
# int divide(int, int, int [*](#))_divide = _mod.divide_divide.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int))_divide.restype = ctypes.c_int
def divide(x, y):
rem = ctypes.c_int()quot = _divide(x, y, rem)
return quot,rem.value
# void avg(double [*](#), int n)# Define a special type for the ‘double [*](#)‘ argumentclass DoubleArrayType:
> def from_param(self, param):> typename = type(param).__name__if hasattr(self, ‘[from_](#)‘ + typename):
> > return getattr(self, ‘[from_](#)‘ + typename)(param)
elif isinstance(param, ctypes.Array):return paramelse:raise TypeError(“Can't convert %s” % typename)> # Cast from array.array objectsdef from_array(self, param):
> > if param.typecode != ‘d':raise TypeError(‘must be an array of doubles')> > ptr, _ = param.buffer_info()return ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double))
> # Cast from lists/tuplesdef from_list(self, param):
> > val = ((ctypes.c_double)*len(param))([*](#)param)return val
> from_tuple = from_list
> # Cast from a numpy arraydef from_ndarray(self, param):
> > return param.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
DoubleArray = DoubleArrayType()_avg = _mod.avg_avg.argtypes = (DoubleArray, ctypes.c_int)_avg.restype = ctypes.c_double
def avg(values):return _avg(values, len(values))
# struct Point { }class Point(ctypes.Structure):
> _fields_ = [(‘x', ctypes.c_double),(‘y', ctypes.c_double)]
# double distance(Point [*](#), Point [*](#))distance = _mod.distancedistance.argtypes = (ctypes.POINTER(Point), ctypes.POINTER(Point))distance.restype = ctypes.c_double
If all goes well, you should be able to load the module and use the resulting C functions.For example:
>>> import sample
>>> sample.gcd(35,42)
7
>>> sample.in_mandel(0,0,500)
1
>>> sample.in_mandel(2.0,1.0,500)
0
>>> sample.divide(42,8)
(5, 2)
>>> sample.avg([1,2,3])
2.0
>>> p1 = sample.Point(1,2)
>>> p2 = sample.Point(4,5)
>>> sample.distance(p1,p2)
4.242640687119285
>>>
## 讨论
There are several aspects of this recipe that warrant some discussion. The first issueconcerns the overall packaging of C and Python code together. If you are using ctypesto access C code that you have compiled yourself, you will need to make sure that theshared library gets placed in a location where the sample.py module can find it. Onepossibility is to put the resulting .so file in the same directory as the supporting Pythoncode. This is what’s shown at the first part of this recipe—sample.py looks at the __file__variable to see where it has been installed, and then constructs a path that points to alibsample.so file in the same directory.If the C library is going to be installed elsewhere, then you’ll have to adjust the pathaccordingly. If the C library is installed as a standard library on your machine, you mightbe able to use the ctypes.util.find_library() function. For example:
>>> from ctypes.util import find_library
>>> find_library('m')
'/usr/lib/libm.dylib'
>>> find_library('pthread')
'/usr/lib/libpthread.dylib'
>>> find_library('sample')
'/usr/local/lib/libsample.so'
>>>
Again, ctypes won’t work at all if it can’t locate the library with the C code. Thus, you’llneed to spend a few minutes thinking about how you want to install things.Once you know where the C library is located, you use ctypes.cdll.LoadLibrary()to load it. The following statement in the solution does this where _path is the fullpathname to the shared library:
_mod = ctypes.cdll.LoadLibrary(_path)
Once a library has been loaded, you need to write statements that extract specific sym‐bols and put type signatures on them. This is what’s happening in code fragments suchas this:
# int in_mandel(double, double, int)in_mandel = _mod.in_mandelin_mandel.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_int)in_mandel.restype = ctypes.c_int
In this code, the .argtypes attribute is a tuple containing the input arguments to afunction, and .restype is the return type. ctypes defines a variety of type objects (e.g.,c_double, c_int, c_short, c_float, etc.) that represent common C data types. Attach‐ing the type signatures is critical if you want to make Python pass the right kinds ofarguments and convert data correctly (if you don’t do this, not only will the code notwork, but you might cause the entire interpreter process to crash).A somewhat tricky part of using ctypes is that the original C code may use idioms thatdon’t map cleanly to Python. The divide() function is a good example because it returnsa value through one of its arguments. Although that’s a common C technique, it’s oftennot clear how it’s supposed to work in Python. For example, you can’t do anythingstraightforward like this:
>>> divide = _mod.divide
>>> divide.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int))
>>> x = 0
>>> divide(10, 3, x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 3: <class 'TypeError'>: expected LP_c_int
instance instead of int
>>>
Even if this did work, it would violate Python’s immutability of integers and probablycause the entire interpreter to be sucked into a black hole. For arguments involvingpointers, you usually have to construct a compatible ctypes object and pass it in likethis:
>>> x = ctypes.c_int()
>>> divide(10, 3, x)
3
>>> x.value
1
>>>
Here an instance of a ctypes.c_int is created and passed in as the pointer object. Unlikea normal Python integer, a c_int object can be mutated. The .value attribute can beused to either retrieve or change the value as desired.
For cases where the C calling convention is “un-Pythonic,” it is common to write a smallwrapper function. In the solution, this code makes the divide() function return thetwo results using a tuple instead:# int divide(int, int, int [*](#))_divide = _mod.divide_divide.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int))_divide.restype = ctypes.c_int
def divide(x, y):rem = ctypes.c_int()quot = _divide(x,y,rem)return quot, rem.value
The avg() function presents a new kind of challenge. The underlying C code expectsto receive a pointer and a length representing an array. However, from the Python side,we must consider the following questions: What is an array? Is it a list? A tuple? Anarray from the array module? A numpy array? Is it all of these? In practice, a Python“array” could take many different forms, and maybe you would like to support multiplepossibilities.The DoubleArrayType class shows how to handle this situation. In this class, a singlemethod from_param() is defined. The role of this method is to take a single parameterand narrow it down to a compatible ctypes object (a pointer to a ctypes.c_double, inthe example). Within from_param(), you are free to do anything that you wish. In thesolution, the typename of the parameter is extracted and used to dispatch to a morespecialized method. For example, if a list is passed, the typename is list and a methodfrom_list() is invoked.For lists and tuples, the from_list() method performs a conversion to a ctypes arrayobject. This looks a little weird, but here is an interactive example of converting a list toa ctypes array:
>>> nums = [1, 2, 3]
>>> a = (ctypes.c_double * len(nums))(*nums)
>>> a
<__main__.c_double_Array_3 object at 0x10069cd40>
>>> a[0]
1.0
>>> a[1]
2.0
>>> a[2]
3.0
>>>
For array objects, the from_array() method extracts the underlying memory pointerand casts it to a ctypes pointer object. For example:
>>> import array
>>> a = array.array('d',[1,2,3])
>>> a
array('d', [1.0, 2.0, 3.0])
>>> ptr_ = a.buffer_info()
>>> ptr
4298687200
>>> ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double))
<__main__.LP_c_double object at 0x10069cd40>
>>>
The from_ndarray() shows comparable conversion code for numpy arrays.By defining the DoubleArrayType class and using it in the type signature of avg(), asshown, the function can accept a variety of different array-like inputs:
>>> import sample
>>> sample.avg([1,2,3])
2.0
>>> sample.avg((1,2,3))
2.0
>>> import array
>>> sample.avg(array.array('d',[1,2,3]))
2.0
>>> import numpy
>>> sample.avg(numpy.array([1.0,2.0,3.0]))
2.0
>>>
The last part of this recipe shows how to work with a simple C structure. For structures,you simply define a class that contains the appropriate fields and types like this:
class Point(ctypes.Structure):_fields_ = [(‘x', ctypes.c_double),(‘y', ctypes.c_double)]
Once defined, you can use the class in type signatures as well as in code that needs toinstantiate and work with the structures. For example:
>>> p1 = sample.Point(1,2)
>>> p2 = sample.Point(4,5)
>>> p1.x
1.0
>>> p1.y
2.0
>>> sample.distance(p1,p2)
4.242640687119285
>>>
A few final comments: ctypes is a useful library to know about if all you’re doing isaccessing a few C functions from Python. However, if you’re trying to access a largelibrary, you might want to look at alternative approaches, such as Swig (described inRecipe 15.9) or Cython (described in Recipe 15.10).
The main problem with a large library is that since ctypes isn’t entirely automatic, you’llhave to spend a fair bit of time writing out all of the type signatures, as shown in theexample. Depending on the complexity of the library, you might also have to write alarge number of small wrapper functions and supporting classes. Also, unless you fullyunderstand all of the low-level details of the C interface, including memory managementand error handling, it is often quite easy to make Python catastrophically crash with asegmentation fault, access violation, or some similar error.As an alternative to ctypes, you might also look at CFFI. CFFI provides much of thesame functionality, but uses C syntax and supports more advanced kinds of C code. Asof this writing, CFFI is still a relatively new project, but its use has been growing rapidly.There has even been some discussion of including it in the Python standard library insome future release. Thus, it’s definitely something to keep an eye on.
- Copyright
- 前言
- 第一章:数据结构和算法
- 1.1 解压序列赋值给多个变量
- 1.2 解压可迭代对象赋值给多个变量
- 1.3 保留最后N个元素
- 1.4 查找最大或最小的N个元素
- 1.5 实现一个优先级队列
- 1.6 字典中的键映射多个值
- 1.7 字典排序
- 1.8 字典的运算
- 1.9 查找两字典的相同点
- 1.10 删除序列相同元素并保持顺序
- 1.11 命名切片
- 1.12 序列中出现次数最多的元素
- 1.13 通过某个关键字排序一个字典列表
- 1.14 排序不支持原生比较的对象
- 1.15 通过某个字段将记录分组
- 1.16 过滤序列元素
- 1.17 从字典中提取子集
- 1.18 映射名称到序列元素
- 1.19 转换并同时计算数据
- 1.20 合并多个字典或映射
- 第二章:字符串和文本
- 2.1 使用多个界定符分割字符串
- 2.2 字符串开头或结尾匹配
- 2.3 用Shell通配符匹配字符串
- 2.4 字符串匹配和搜索
- 2.5 字符串搜索和替换
- 2.6 字符串忽略大小写的搜索替换
- 2.7 最短匹配模式
- 2.8 多行匹配模式
- 2.9 将Unicode文本标准化
- 2.10 在正则式中使用Unicode
- 2.11 删除字符串中不需要的字符
- 2.12 审查清理文本字符串
- 2.13 字符串对齐
- 2.14 合并拼接字符串
- 2.15 字符串中插入变量
- 2.16 以指定列宽格式化字符串
- 2.17 在字符串中处理html和xml
- 2.18 字符串令牌解析
- 2.19 实现一个简单的递归下降分析器
- 2.20 字节字符串上的字符串操作
- 第三章:数字日期和时间
- 3.1 数字的四舍五入
- 3.2 执行精确的浮点数运算
- 3.3 数字的格式化输出
- 3.4 二八十六进制整数
- 3.5 字节到大整数的打包与解包
- 3.6 复数的数学运算
- 3.7 无穷大与NaN
- 3.8 分数运算
- 3.9 大型数组运算
- 3.10 矩阵与线性代数运算
- 3.11 随机选择
- 3.12 基本的日期与时间转换
- 3.13 计算最后一个周五的日期
- 3.14 计算当前月份的日期范围
- 3.15 字符串转换为日期
- 3.16 结合时区的日期操作
- 第四章:迭代器与生成器
- 4.1 手动遍历迭代器
- 4.2 代理迭代
- 4.3 使用生成器创建新的迭代模式
- 4.4 实现迭代器协议
- 4.5 反向迭代
- 4.6 带有外部状态的生成器函数
- 4.7 迭代器切片
- 4.8 跳过可迭代对象的开始部分
- 4.9 排列组合的迭代
- 4.10 序列上索引值迭代
- 4.11 同时迭代多个序列
- 4.12 不同集合上元素的迭代
- 4.13 创建数据处理管道
- 4.14 展开嵌套的序列
- 4.15 顺序迭代合并后的排序迭代对象
- 4.16 迭代器代替while无限循环
- 第五章:文件与IO
- 5.1 读写文本数据
- 5.2 打印输出至文件中
- 5.3 使用其他分隔符或行终止符打印
- 5.4 读写字节数据
- 5.5 文件不存在才能写入
- 5.6 字符串的I/O操作
- 5.7 读写压缩文件
- 5.8 固定大小记录的文件迭代
- 5.9 读取二进制数据到可变缓冲区中
- 5.10 内存映射的二进制文件
- 5.11 文件路径名的操作
- 5.12 测试文件是否存在
- 5.13 获取文件夹中的文件列表
- 5.14 忽略文件名编码
- 5.15 打印不合法的文件名
- 5.16 增加或改变已打开文件的编码
- 5.17 将字节写入文本文件
- 5.18 将文件描述符包装成文件对象
- 5.19 创建临时文件和文件夹
- 5.20 与串行端口的数据通信
- 5.21 序列化Python对象
- 第六章:数据编码和处理
- 6.1 读写CSV数据
- 6.2 读写JSON数据
- 6.3 解析简单的XML数据
- 6.4 增量式解析大型XML文件
- 6.5 将字典转换为XML
- 6.6 解析和修改XML
- 6.7 利用命名空间解析XML文档
- 6.8 与关系型数据库的交互
- 6.9 编码和解码十六进制数
- 6.10 编码解码Base64数据
- 6.11 读写二进制数组数据
- 6.12 读取嵌套和可变长二进制数据
- 6.13 数据的累加与统计操作
- 第七章:函数
- 7.1 可接受任意数量参数的函数
- 7.2 只接受关键字参数的函数
- 7.3 给函数参数增加元信息
- 7.4 返回多个值的函数
- 7.5 定义有默认参数的函数
- 7.6 定义匿名或内联函数
- 7.7 匿名函数捕获变量值
- 7.8 减少可调用对象的参数个数
- 7.9 将单方法的类转换为函数
- 7.10 带额外状态信息的回调函数
- 7.11 内联回调函数
- 7.12 访问闭包中定义的变量
- 第八章:类与对象
- 8.1 改变对象的字符串显示
- 8.2 自定义字符串的格式化
- 8.3 让对象支持上下文管理协议
- 8.4 创建大量对象时节省内存方法
- 8.5 在类中封装属性名
- 8.6 创建可管理的属性
- 8.7 调用父类方法
- 8.8 子类中扩展property
- 8.9 创建新的类或实例属性
- 8.10 使用延迟计算属性
- 8.11 简化数据结构的初始化
- 8.12 定义接口或者抽象基类
- 8.13 实现数据模型的类型约束
- 8.14 实现自定义容器
- 8.15 属性的代理访问
- 8.16 在类中定义多个构造器
- 8.17 创建不调用init方法的实例
- 8.18 利用Mixins扩展类功能
- 8.19 实现状态对象或者状态机
- 8.20 通过字符串调用对象方法
- 8.21 实现访问者模式
- 8.22 不用递归实现访问者模式
- 8.23 循环引用数据结构的内存管理
- 8.24 让类支持比较操作
- 8.25 创建缓存实例
- 第九章:元编程
- 9.1 在函数上添加包装器
- 9.2 创建装饰器时保留函数元信息
- 9.3 解除一个装饰器
- 9.4 定义一个带参数的装饰器
- 9.5 可自定义属性的装饰器
- 9.6 带可选参数的装饰器
- 9.7 利用装饰器强制函数上的类型检查
- 9.8 将装饰器定义为类的一部分
- 9.9 将装饰器定义为类
- 9.10 为类和静态方法提供装饰器
- 9.11 装饰器为被包装函数增加参数
- 9.12 使用装饰器扩充类的功能
- 9.13 使用元类控制实例的创建
- 9.14 捕获类的属性定义顺序
- 9.15 定义有可选参数的元类
- 9.16 *args和**kwargs的强制参数签名
- 9.17 在类上强制使用编程规约
- 9.18 以编程方式定义类
- 9.19 在定义的时候初始化类的成员
- 9.20 利用函数注解实现方法重载
- 9.21 避免重复的属性方法
- 9.22 定义上下文管理器的简单方法
- 9.23 在局部变量域中执行代码
- 9.24 解析与分析Python源码
- 9.25 拆解Python字节码
- 第十章:模块与包
- 10.1 构建一个模块的层级包
- 10.2 控制模块被全部导入的内容
- 10.3 使用相对路径名导入包中子模块
- 10.4 将模块分割成多个文件
- 10.5 利用命名空间导入目录分散的代码
- 10.6 重新加载模块
- 10.7 运行目录或压缩文件
- 10.8 读取位于包中的数据文件
- 10.9 将文件夹加入到sys.path
- 10.10 通过字符串名导入模块
- 10.11 通过导入钩子远程加载模块
- 10.12 导入模块的同时修改模块
- 10.13 安装私有的包
- 10.14 创建新的Python环境
- 10.15 分发包
- 第十一章:网络与Web编程
- 11.1 作为客户端与HTTP服务交互
- 11.2 创建TCP服务器
- 11.3 创建UDP服务器
- 11.4 通过CIDR地址生成对应的IP地址集
- 11.5 生成一个简单的REST接口
- 11.6 通过XML-RPC实现简单的远程调用
- 11.7 在不同的Python解释器之间交互
- 11.8 实现远程方法调用
- 11.9 简单的客户端认证
- 11.10 在网络服务中加入SSL
- 11.11 进程间传递Socket文件描述符
- 11.12 理解事件驱动的IO
- 11.13 发送与接收大型数组
- 第十二章:并发编程
- 12.1 启动与停止线程
- 12.2 判断线程是否已经启动
- 12.3 线程间的通信
- 12.4 给关键部分加锁
- 12.5 防止死锁的加锁机制
- 12.6 保存线程的状态信息
- 12.7 创建一个线程池
- 12.8 简单的并行编程
- 12.9 Python的全局锁问题
- 12.10 定义一个Actor任务
- 12.11 实现消息发布/订阅模型
- 12.12 使用生成器代替线程
- 12.13 多个线程队列轮询
- 12.14 在Unix系统上面启动守护进程
- 第十三章:脚本编程与系统管理
- 13.1 通过重定向/管道/文件接受输入
- 13.2 终止程序并给出错误信息
- 13.3 解析命令行选项
- 13.4 运行时弹出密码输入提示
- 13.5 获取终端的大小
- 13.6 执行外部命令并获取它的输出
- 13.7 复制或者移动文件和目录
- 13.8 创建和解压压缩文件
- 13.9 通过文件名查找文件
- 13.10 读取配置文件
- 13.11 给简单脚本增加日志功能
- 13.12 给内库增加日志功能
- 13.13 记录程序执行的时间
- 13.14 限制内存和CPU的使用量
- 13.15 启动一个WEB浏览器
- 第十四章:测试调试和异常
- 14.1 测试输出到标准输出上
- 14.2 在单元测试中给对象打补丁
- 14.3 在单元测试中测试异常情况
- 14.4 将测试输出用日志记录到文件中
- 14.5 忽略或者期望测试失败
- 14.6 处理多个异常
- 14.7 捕获所有异常
- 14.8 创建自定义异常
- 14.9 捕获异常后抛出另外的异常
- 14.10 重新抛出最后的异常
- 14.11 输出警告信息
- 14.12 调试基本的程序崩溃错误
- 14.13 给你的程序做基准测试
- 14.14 让你的程序跑的更快
- 第十五章:C语言扩展
- 15.1 使用ctypes访问C代码
- 15.2 简单的C扩展模块
- 15.3 一个操作数组的扩展函数
- 15.4 在C扩展模块中操作隐形指针
- 15.5 从扩张模块中定义和导出C的API
- 15.6 从C语言中调用Python代码
- 15.7 从C扩展中释放全局锁
- 15.8 C和Python中的线程混用
- 15.9 用WSIG包装C代码
- 15.10 用Cython包装C代码
- 15.11 用Cython写高性能的数组操作
- 15.12 将函数指针转换为可调用对象
- 15.13 传递NULL结尾的字符串给C函数库
- 15.14 传递Unicode字符串给C函数库
- 15.15 C字符串转换为Python字符串
- 15.16 不确定编码格式的C字符串
- 15.17 传递文件名给C扩展
- 15.18 传递已打开的文件给C扩展
- 15.19 从C语言中读取类文件对象
- 15.20 处理C语言中的可迭代对象
- 15.21 诊断分析代码错误
- 附录A
- 关于译者
- Roadmap