下面是来自 C 的结构,我正在尝试转换为 Python,并使用 Socket 发送结构
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);
我已经使用 namedtuple 创建了 Python 结构,并使用套接字发送这个结构。但不幸的是失败了。
Python:
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "sMark nPackLen nFlag nGisIp nPort sData sEnd")
编辑,回复下面的答案
弄清楚后,python 3.x 必须添加 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)
附加问题
下面是使用结构发送的数据包
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
2个未知字节怎么来的?