|
sRGB
发表于 2021-12-27 12:28
本帖最后由 sRGB 于 2021-12-27 12:35 编辑
Python 的外部函数库 ctypes
ctypes 是 Python 的外部函数库。它提供了与 C 兼容的数据类型,并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进行封装。

本文只用到 ctypes 模块中的结构体 Structure 与 C 兼容数据类型
Python 的外部函数库 ctypes 之 结构体和联合
结构体和联合必须继承自 ctypes 模块中的 Structure 和 Union 。子类必须定义 fields 属性。 fields 是一个二元组列表,二元组中包含 field name 和 field type 。
type 字段必须是一个 ctypes 类型,比如 c_int,或者其他 ctypes 类型: 结构体、联合、数组、指针。
这是一个简单的 POINT 结构体,它包含名称为 x 和 y 的两个变量,还展示了如何通过构造函数初始化结构体。
[Python] 纯文本查看 复制代码 from ctypes import *
class POINT(Structure):
_fields_ = [("x", c_int),
("y", c_int)]
point = POINT(10, 20)
print(point.x, point.y)
point = POINT(y=5)
print(point.x, point.y)
POINT(1, 2, 3)
python读写C语言数据结构.py
实验源码 https://github.com/hongwenjun/srgb/blob/master/python/python%E8%AF%BB%E5%86%99C%E8%AF%AD%E8%A8%80%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84.py
C 语言定义的结构体 struct gps 在Python中对应写成 class Location(Structure)
[Python] 纯文本查看 复制代码 struct gps {[/b] double x; double y; };
class Location(Structure):
_fields_ = [('lon', c_double), ('lat', c_double)]
pybin.py Python 使用 C数据结构,把一个gps坐标写到文件中。

fread.c 使用C语言程序读取数据文件,验证写文件是否正确

pybin_read.py Python 读取C数据结构文件后,需要使用 struct 库进行二进制数据转换

将字节串解读为打包的二进制数据 struct
) |
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|