How to implement a union (C data type) in Python?

chads lamote1 at netscape.net
Mon Mar 8 13:24:26 EST 2004


Thomas Heller wrote:

> lamote1 at netscape.net (chads) writes:
> 
> 
>>How would one implement a union (C data type) in Python, given this
>>simple example?
>>
>>union {
>>   struct {
>>      int size;
>>      float time;
>>   } var1;
>>   struct {
>>      char initial;
>>      float time;
>>   } var2;
>>};
> 
> 
> With ctypes ;-)
> 
> from ctypes import *
> 
> class MyUnion(Union):
> 
>     class struct_1(Structure):
>         _fields_ = [("size", c_int),
>                     ("time", c_float)]
> 
>     class struct_2(Structure):
>         _fields_ = [("initial", c_char),
>                     ("time", c_float)]
> 
>     _fields_ = [("var1", struct_1),
>                 ("var2", struct_2)]
> 
> print sizeof(MyUnion)
> 
> On Windows, this prints 8.
> 
> Thomas
> 
> 

Thank you.




More information about the Python-list mailing list