python alternatives to C structs??

Dave Angel davea at ieee.org
Sun Apr 19 00:06:48 EDT 2009


Aaron Brady wrote:
> On Apr 18, 2:25 pm, KoolD <sourya... at gmail.com> wrote:
>   
>> Hey all,
>> I need to convert a C code to python please help me figure out how to
>> do
>> it.
>> Suppose the C program's like:
>>
>> ------------------------------------
>> typedef struct _str
>> {
>> int a;
>> char *b;
>> int c;}str;
>>
>> int main()
>> {
>> str mbr;
>> fd=en("/dev/sda",O_RDONLY);
>> read(fd,&mbr,sizeof(str));}
>>
>> ------------------------------------
>>
>> Is there a way to code it in python.
>>
>> Thanks
>> Sourya
>>     
>
> There is the 'ctypes' module, but you might also need 'mmap', for the
> 'read( &mbr )' operation.
>
>   
A  bigger problem is reading that pointer.  Reading a pointer from a 
device is only meaningful if the device has mapped memory, and then only 
if you map it to the same address it was mapped originally.

But getting the ints is pretty easy.  Use the struct module.  It allows 
you to interpret byte strings according to C types.

So do the read with the usual open().read logic.   Size could be 
anywhere from 6 to 48 bytes, depending on the version and platform of C 
you're working from.  It might even depend on the alignment settings of 
the particular C compile.

Then take the result string, and do a struct.unpack() operation on it.






More information about the Python-list mailing list