简体   繁体   English

如何使用 python 创建结构 c 并在套接字上发送

[英]How create struct c with python and send on socket

This struct is C code:这个结构是C代码:

struct my_struct_in_c
{
    int port1;
    int port2;
    int port3;
    char ip1[20];
    char ip2[20];
};

how convert above struct c to python?如何将上述结构 c 转换为 python?


I have test this codes but does not correct deserializer in c:我已经测试了这些代码,但没有更正 c 中的反序列化器:

code1 (does not correct deserializer in c): code1(不纠正 c 中的反序列化器):

res = pack("iii%ss%ss" % (20, 20), 2001, 2002, 2003, b"192.168.1.1", b"192.168.1.2")

code2 (does not correct deserializer in c): code2(不纠正 c 中的反序列化器):

import struct
from collections import namedtuple

format_ = "iii%ss%ss" % (20, 20)

MyStruct = namedtuple("my_struct_in_c", "port1 port2 port3 ip1 ip2")
tuple_to_send = MyStruct(port1=2000,
                         port2=2001,
                         port3=2002,
                         ip1=b"192.168.1.1",
                         ip2=b"192.168.1.2")

string_to_send = struct.pack(format_, *tuple_to_send._asdict().values())

As soon as you want to send data over a socket, you have a serialization/deserialization problem.只要您想通过套接字发送数据,就会遇到序列化/反序列化问题。 The Python struct module fully handles it, and you can (or must) specify the size of the different elements and the byte ordering (endianness). Python struct模块完全处理它,您可以(或必须)指定不同元素的大小和字节顺序(字节序)。

C side, beginners often just cast a native struct to a char array and directly use read or write on that... with the unspecified endianness and possible padding problem. C 方面,初学者通常只是将本机结构转换为 char 数组并直接在其上使用读取或写入......具有未指定的字节顺序和可能的填充问题。

What I mean is that you should never rely on the way C internally stores the struct, but always (de)serialize individual elements in a well defined (size and endianness) way.我的意思是,您永远不应该依赖 C内部存储结构的方式,而是始终以明确定义(大小和字节顺序)的方式(反)序列化单个元素。

Long story made short, without knowing more on the C side, I cannot tell you how you should serialize Python side.长话短说,在不了解 C 方面的更多信息的情况下,我无法告诉您应该如何序列化 Python 方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM