tags:

views:

71

answers:

1

Hi everybody,

I am programming an application to send data using UDP sockets with Python 3.1.

The command socket.send requires data in bytes format.

The problem I am having is that the package I have to send has three different fields, the first one contains a 16 bits integer variable (c_ushort) and so does the second field whereas the third one is an string whose length can go up to 900 characters.

I decided then to create an struct that contains these three fields:

class PHAL_msg(Structure):
    _fields_ = [("Port", c_ushort),
                ("Size", c_ushort),
                ("Text", c_wchar_p)]

I would expect I could send this object by just converting it to a bytes object:

Msg_TX = PHAL_msg(Port=PHAL_ADDRESS, Size=PAYLOAD_SIZE, Text='HELLO woRLD!')
socket.send(bytes(Msg_TX))

, but it does not work.

Any idea how this could be done?

Regards

+1  A: 

You need to serialize your class, use pickle.

class Blah:
    def __init__(self,mynum, mystr):
        self.mynum = mynum
        self.mystr = mystr

a = Blah(3,"blahblah")
#bytes(a) # this will fail with "TypeError: 'Blah' object is not iterable"

import pickle
b = pickle.dumps(a) # turn it into a bytestring
c = pickle.loads(b) # and back to the class

print("a: ", a.__repr__(), a.mynum, a.mystr)
print("pickled....")
print("b: type is:",type(b)) # note it's already in bytes.
print(b.__repr__())
print("unpickled....")
print("c: ", c.__repr__(), c.mynum, c.mystr)

Output:

a:  <__main__.Blah object at 0x00BCB470> 3 blahblah
pickled....
b: type is: <class 'bytes'>
b'\x80\x03c__main__\nBlah\nq\x00)\x81q\x01}q\x02(X\x
05\x00\x00\x00mystrq\x03X\x08\x00\x00\x00blahblahq\x
04X\x05\x00\x00\x00mynumq\x05K\x03ub.'
unpickled....
c:  <__main__.Blah object at 0x00BCB950> 3 blahblah
Nick T
Hi Nick,thank you for your answer. However, I see that the byte string to be sent with the socket (Blah in your case)contains not just the values of the variables mynum and mystr but also other stuff as I can see above. All I can send is the values of the variables in the struct.
Joan