Python从小白到高手实现系列三百二十五:使用ctypes 调用C 函数

文章介绍了如何在Python中通过ctypes模块加载C库并使用其功能,特别关注了如何处理Python类型与C类型之间的转换,以及如何创建和使用C数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当库成功加载时,通用的模式是将其存储为与库名称相同的模块级变量。函数可以作为对
象属性访问,因此调用它们就像调用从任何其他导入模块导入的Python 函数一样,如下所示:

import ctypes
from ctypes.util import find_library

libc = 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

断水流大撕兄

你的鼓励,就是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值