在 C 语言中我们有
struct temp
{
unisgned int i[10];
char a[2][10];
}temp;
像这样我正在 python 中制作一个结构:
integer_aray=[1,2,3,4,5]
string_array=["hello","world"]
format_="Qs"
temp = namedtuple("temp","i a")
temp_tuple = temp(i=integer_array,a=string_array)
string_to_send = struct.pack(format_, *temp_tuple)
当我尝试像这样的 python 2.7 时出现错误
string_to_send = struct.pack(format_, *temp_tuple)
error: cannot convert argument to integer
我必须将 python 结构作为整数数组和字符串数组发送。有什么方法可以在不使用 ctypes 的情况下发送数组吗?
最佳答案
如果你想打包 C 结构体的等价物
struct temp
{
unsigned int i[10];
char a[2][10];
};
您将使用格式“10I10s10s”
,其中10I
代表按 native 顺序排列的10个4字节无符号整数,每个10s
代表大小为 10 的字节字符串。
在Python3中,你可以这样写:
l = list(range(1, 11)) # [1,2,3,4,5,6,7,8,9,10]
temp = struct.pack("10I10s10s", *l, b"hello", b"world")
print(temp)
它会给出(在小端 ASCII 平台上):
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00hello\x00\x00\x00\x00\x00world\x00\x00\x00\x00\x00'
它与 32 位小端系统上的 C temp
结构兼容。
关于python - 在python中形成包含整数数组、字符串列表的结构包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47886472/