Ankit Duggal
Ankit Duggal

Reputation: 1

Using c style structure in Python

I am writing a script in python and have worked only on C and C++ all my life. What i want is to take in some parameters from caller and then create a 32 byte packet. Packet contains some bytes, some DWORDS, some bit fields etc. So i want to create this packet and then copy it over byte-by-byte (this is important) into a buffer which is allocated by a low level driver.

In C/C++ this is straight forward. Define a struct, program the fields and then read it byte by byte and copy it over to the buffer.

How can i do this in python? Looks like i can't define a class/struct which contains my 32 byte packet and then iterate over its members to copy them down byte by byte.

Any suggestions?

Upvotes: 0

Views: 371

Answers (1)

maxy
maxy

Reputation: 5467

Python 3 has special type for binary strings called bytes, as opposed to unicode strings. This is in contrast to Python 2, where this was the default string type.

The simplest way to create one is struct.pack with its format strings. For example, if you have an unsigned short followed by a signed short in your struct and you want to encode them in network byte order (aka big endian):

import struct
data = struct.pack('>Hh', 0xAFFE, -5)

This creates the byte string b'\xaf\xfe\xff\xfb'. You can access the first byte with data[0] or iterate over them with for byte in data: or get len(data) etc.

You can write them into a (device) file in binary mode like this:

with open('/dev/myfile', 'wb') as f:
    f.write(data)

Or send them over an UDP socket:

from socket import socket, AF_INET, SOCK_DGRAM
sock = socket(AF_INET, SOCK_DGRAM)
sock.sendto(data, ('127.0.0.1', 9999))

The Python 3 struct module has more examples.

Upvotes: 2

Related Questions