Python ctypes
时间: 2025-01-13 10:52:52 浏览: 49
### Python 中 `ctypes` 库的使用教程
#### 加载共享库或DLL文件
为了能够访问外部函数,首先需要加载相应的动态链接库(DLL)或者共享对象(`.so` 文件)。这可以通过 `cdll` 或者 `windll` 来完成,在 Unix 类系统上通常会用到前者而在 Windows 上则更多地依赖后者。
```python
from ctypes import cdll, windll
# 对于 Linux/Unix/MacOS 的 .so 文件
libc = cdll.LoadLibrary('libexample.so')
# 对于 Windows 的 .dll 文件
msvcrt = windll.msvcrt # 这里假设 msvcrt.dll 已经存在于系统的路径中[^1]
```
#### 定义参数类型和返回值类型
当调用了来自 C/C++ 编写的库之后,可能还需要指定这些函数接受什么样的输入以及它们应该给出什么类型的输出。为此目的服务的就是 `.argtypes` 和 `.restype` 属性:
```python
import ctypes
# 假设有一个名为 'my_function' 的 C 函数它接收两个整数并返回一个浮点型的结果
libc.my_function.argtypes = (ctypes.c_int, ctypes.c_int)
libc.my_function.restype = ctypes.c_float
result = libc.my_function(5, 7) # 调用该函数并将结果存储起来[^2]
```
#### 创建结构体和联合体
如果目标 API 需要传递复杂数据结构给被调用方,则可以利用 `Structure` 及其子类来定义自定义的数据布局;同样也可以创建 `Union` 子类用于表示内存中共存多个字段的情况。
```python
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]
point_instance = Point()
print(point_instance.x, point_instance.y)
# 如果有共同占用同一块内存区域的需求时可采用 Union
class DataUnion(ctypes.Union):
_fields_ = [
('integer', ctypes.c_long),
('float_value', ctypes.c_float * 2)]
data_union_example = DataUnion(integer=0xAABBCCDD)
print(data_union_example.integer) # 输出十六进制数值 AABBCDDE
print(list(data_union_example.float_value)) # 将 union 解释成 float 数组的形式打印出来[^3]
```
阅读全文
相关推荐
















