python - 如何从 python 数组访问 C 结构

标签 python c struct wireless beagleboneblack

我是 python 的新手,一直在尝试为这个特定项目学习它。我正在做的是使用本质上是一个 arduino 克隆和一个 NRf24 收发器来无线发送以下结构。

struct SENSOR{
  float sensor1;
  float sensor2;
  float sensor3;
};

struct HEADER{
  long type;
  long hops;
  long src;
  long ID;
  SENSOR sensor;
};

我使用带有 NRf24 的 beaglebone black 来接收它。在 BBB 上,收发器由 python 驱动(因为 BBB 和我正在使用的 radio 已经有(相对)大量的代码库)。

在 arduino 方面,它显示结构的长度为 28,这也是我在 python 方面收到的。我想不通的是如何将存储在数组中的接收数据移动为可用格式。

python 方面:

#Receive Data
recv_buffer = []
radio.read(recv_buffer)

这是我在 python 端收到的内容

[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 51, 51, 163, 64, 51, 51, 195, 64, 51, 51, 227, 64]

并在arduino端发送

header.type = 1;
header.hops = 2;
header.src = 3;
header.ID = 4;
header.sensor.sensor1 = 5.1;
header.sensor.sensor2 = 6.1;
header.sensor.sensor3 = 7.1;

我一直在研究 ctypes 库并可能对其使用 unpack,但无法使其正常工作。我感谢任何帮助。

最佳答案

使用 struct模块。

首先,将您的整数(实际上是字节)值数组转换为字符串表示形式,例如

''.join(chr(c) for c in recv_buffer)

...然后将该字符串传递给 struct.unpack 函数,传递格式字符以指定需要如何将字符串解析为实际值。

>>> import struct
>>> b = [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 51, 51, 163, 64, 51, 51, 195, 64, 51, 51, 227, 64]
>>> struct.unpack("llllfff", ''.join(chr(c) for c in recv_buffer))
(1, 2, 3, 4, 5.0999999046325684, 6.0999999046325684, 7.0999999046325684)

关于python - 如何从 python 数组访问 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20910886/

相关文章:

python - 如何使用map函数将数据框中的所有负数转换为python pandas中所有数字的平均值?

python - 获取 nosetests 配置选项

C初学者: Need explanation of error messages from "ideone"

c - 多个数据结构的单个 malloc 调用

检查元素是否存在于C中的结构中

python - Pandas 通过部分字符串匹配大小将列分配给数组维度错误

python - 如何判断数据是否有效

c - 抽象解释器如何工作?

c++ - 有什么办法可以反编译Linux .so?

c - 结构体没有名为...的成员和预期的标识符