Skip to content Skip to sidebar Skip to footer

Python : Socket Sending Struct(having C Stuct As Example)

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 fla

Solution 1:

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.

from collections import namedtuple
import pickle # or cPickle, it's faster
MyStruct = namedtuple("MyStruct", "sMark nPackLen nFlag nGisIp nPort sData sEnd")

tuple_to_send = MyStruct(sMark="abcdef", nPackLen=...)
string_to_send = pickle.dumps(tuple_to_send)

There are two flavors of pickle, pickle and cPickle. 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

format_ = "6shhih50s2s"

So you can do:

import struct
from collections import namedtuple

format_ ="6shhih50s2s"MyStruct= namedtuple("MyStruct", "sMark nPackLen nFlag nGisIp nPort sData sEnd")
tuple_to_send =MyStruct(sMark="\r\n{}".format("*KW"), 
                     nPackLen=struct.calcsize(format_),
                     nFlag=0x0002,
                     nGisIp=0,
                     nPort=0,
                     sData="*KW,NR09G05133,015,080756,#",
                     sEnd="\r\n")


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

BTW: namedtuples are immutable, i.e., you cannot do

tuple_to_send.sMark = "bcdefg"

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.

import struct
from collections import namedtuple

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=b"\r\n")


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

Post a Comment for "Python : Socket Sending Struct(having C Stuct As Example)"