This struct is C code:
struct my_struct_in_c
{
int port1;
int port2;
int port3;
char ip1[20];
char ip2[20];
};
how convert above struct c to python?
I have test this codes but does not correct deserializer in c:
code1 (does not correct deserializer in 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):
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).
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.
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.
Long story made short, without knowing more on the C side, I cannot tell you how you should serialize Python side.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.