How to convert/encode a custom object to bytes/bytearray?

I have the following python class:

class Header:
     id
     len
     def __init__(self, id, len):
         self.id = id
         self.len = len

h = Header(1, 10)

How can I convert/encode an instance of this class, h to bytes or bytearray, which can be written, for example to a socket?

To give a little more perspective I need to write this object to an unix domain socket where a C program is listening to receive the above object (it defines the above struct exactly as above, with same number/type of fields). Encoding by pickle.dump(...) does not work.



Read more here: https://stackoverflow.com/questions/66329134/how-to-convert-encode-a-custom-object-to-bytes-bytearray

Content Attribution

This content was originally published by Curious at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: