Назначение
Доставка массива структуры из модуля python в модуль c.
Метод
Использование типов Pythonвызывать c api для передачи данных.
Steps
- Объявить прототип структуры в python;(проход, строка 4-9)
- Определить массив структур;(передача, строка 16-17)
- Заполнить значения в этом массиве;(ошибка, строка 30)
C Декларация API
injectNodes(int nodeNum, struct node *pNode);
struct node {
uint16_t id;
uint8_t version;
uint8_t depth;
};
Код Python
#!/bin/python3
import pdb
from ctypes import *
class Node(Structure):
_field_ = [
("id", c_uint16),
("version", c_uint8),
("depth", c_uint8)
]
dics = [{'ID': '3', 'VERSION': '180', 'DEPTH': '924'},
{'ID': '9', 'VERSION': '180', 'DEPTH': '269'},
{'ID': '2', 'VERSION': '180', 'DEPTH': '537'}]
nodeNum = len(dics)
NODES = Node * nodeNum
nodes = NODES()
for j in range(nodeNum):
print(dics[j])
node = Node()
node.id = int(dics[j]["ID"])
node.version = int(dics[j]["VERSION"])
node.depth = int(dics[j]["DEPTH"])
print("id", node.id)
print("version", node.version)
print("depth", node.depth)
nodes[j] = node
print("id", nodes[j].id)
print("version", nodes[j].version)
print("depth", nodes[j].depth)
print(nodes)
Ожидаемые результаты
{'ID': '3', 'DEPTH': '924', 'VERSION': '180'}
id 3
version 180
depth 924
id 3
version 180
depth 924
{'ID': '9', 'DEPTH': '269', 'VERSION': '180'}
id 9
version 180
depth 269
id 9
version 180
depth 269
{'ID': '2', 'DEPTH': '537', 'VERSION': '180'}
id 2
version 180
depth 537
id 2
version 180
depth 537
Фактические результаты
{'ID': '3', 'DEPTH': '924', 'VERSION': '180'}
id 3
version 180
depth 924
Traceback (most recent call last):
File "array_test.py", line 28, in <module>
print("id", nodes[j].id)
AttributeError: 'Node' object has no attribute 'id'