Below Are Struct from C,and i m trying Convert to Python,
and use Socket to sending out the struct
C:
struct CommandReq
{
char sMark[6]; //start flag\r\n*KW
short nPackLen; //packet length
short nFlag; //command ID 0x0002
int nGisIp; //GIS port
short nPort; //GIS Port
char sData[50]; //command string
char sEnd[2]; //end flag "\r\n"
};
//source code
CommandReq stResq;
memset(&stResq, 0, sizeof(stResq));
sprintf(stResq.sMark, "\r\n%s", "*KW");
stResq.nFlag = 0x0002;
stResq.nPackLen = sizeof(stResq);
stResq.nGisIp = 0;
stResq.nPort = 0;
strcpy(stResq.sData, "*KW,CC09C00001,015,080756,#");
strncpy(stResq.sEnd, "\r\n", 2);
I have created Python struct using namedtuple,and use socket to send this struct.
but unfortunately failed.
Python:
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "sMark nPackLen nFlag nGisIp nPort sData sEnd")
Edit, in reply to answer below
after figure out, python 3.x must be added string .encode(“ascii”)
format_ = "6shhih50s2s"
MyStruct = namedtuple("MyStruct", "sMark nPackLen nFlag nGisIp nPort sData sEnd")
tuple_to_send = MyStruct(sMark="\r\n{}".format("*KW").encode("ascii"),
nPackLen=struct.calcsize(format_),
nFlag=0x0002,
nGisIp=0,
nPort=0,
sData= "*KW,NR09G05133,015,080756,#".encode("ascii"),
sEnd="\r\n".encode("ascii"))
string_to_send = struct.pack(format_, *tuple_to_send._asdict().values()
socket.sendto(string_to_send, self.client_address)
Additional Question
below is the packet are sending out with the struct
format_ = "6shhih50s2s" //total bytes should be 68 bytes?
0d0a2a4b5700 //6 char \r\n*KW
4600 // packet length 70 bytes
0200 //command ID 0x0002,short 2 bytes
00000000 //GIS port is integer 4 bytes
0000 //GIS Port short 2 bytes
0000 //unknown??what is this?
2a4b572c4e5230394730353133332c3031352c3038303735362c230000000000000000000000000000000000000000000000 //sData[50] char 50 bytes
0d0a //sEnd 2 char,2 bytes
how come the 2 unknown bytes??
namedtuple isn’t really comparable to a c-struct. If you are used to using structs, you can have a look at the
struct-module to convert structured information to a string.In general, Pythonistas prefer using the
pickle-module for serialization.There are two flavors of pickle,
pickleandcPickle. The latter is faster, but is only available in CPython (which most programmers use), while pickle is also available in Jython, IronPython, …If you want to stick to struct (e.g., because the other side expects this format), your format string will be
So you can do:
BTW: namedtuples are immutable, i.e., you cannot do
to change some property. If you need such behavior, you must create a class.
Edit
For Python 3, string-treatment has changed. Conversion from unicode to bytes has to be performed, e.g.