Bit fields

Skip Montanaro skip at mojam.com
Mon Aug 30 15:06:12 EDT 1999


    Archer> I'm writing some extensions to set up a general SCSI oriented
    Archer> test platform in Python.  Obviously there's a certain amount of
    Archer> C work that has to be done, but I would like to do one of the
    Archer> following:

    Archer> A. access bit fields from a C struct that is returned to Python
    Archer> as a string

This is quite doable.  Python supports the bitwise operators you're familiar
with in C and the struct module lets you pack and unpack C struct info into
and out of Python strings.

    Archer> B. encapsulate the structs as classes with all of the methods
    Archer> implemented in C (this would appear to be possible but the
    Archer> doc is mute).

Also easily doable.  The simplest way I know of is to write an extension
module in C that implements the various methods you are interested in and
then just delegate to them from the actual Python methods, e.g.:

    scsi.py:

	import scsiop		# the extension module containing bit ops

	class SCSI:
	    def __init__(self, ...):
		pass

	    def get_SCSI_id(self, packed):
		"""extract SCSI id from packed string"""
		SCSI_id = scsiop.get_SCSI_id(packed)

In scsiop.c you'd implement interesting functions.  This technique shouldn't
be necessary just to extract bitfields from structs packed into strings, but
may come in handy in other places.

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/~skip/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list