2012-11-08 8 views
9

Ho appena iniziato a lavorare con Python e mi chiedo come dovrei definire i sindacati con python (usando i ctype)? Spero di avere ragione, i sindacati sono supportati dai ctype. Ad esempio, come il seguente codice di c è in pythoncome usare i sindacati con python?

struct test 
{ 
char something[10]; 
int status; 
}; 

struct test2 
{ 
char else[10]; 
int status; 
int alive; 
}; 

union tests 
{ 
struct test a; 
struct test2 b; 
}; 

struct tester 
{ 
char more_chars[20]; 
int magic; 
union tests f; 
}; 

Thx, esempio semplice aggiunto se qualcun altro sta cercando la stessa risposta

from ctypes import * 

class POINT(Structure): 
    _fields_ = [("x", c_int), 
       ("y", c_int)] 

class POINT_1(Structure): 
    _fields_ = [("x", c_int), 
       ("y", c_int), 
       ("z",c_int)] 

class POINT_UNION(Union): 
    _fields_ = [("a", POINT), 
       ("b", POINT_1)] 

class TEST(Structure): 
    _fields_ = [("magic", c_int), 
       ("my_union", POINT_UNION)] 

testing = TEST() 
testing.magic = 10; 
testing.my_union.b.x=100 
testing.my_union.b.y=200 
testing.my_union.b.z=300 

risposta

5

Dai uno sguardo allo ctypes tutorial. Utilizzi la classe ctypes.Union:

class test(ctypes.Structure): 
    # ... 
class test2(ctypes.Structure): 
    # ... 

class tests(ctypes.Union): 
    _fields_ = [("a", test), 
       ("b", test2)] 
+1

Grazie a tutti e due. Dovrei leggere più attentamente le informazioni di questo tipo :) – Juster

2

È sufficiente creare una classe che eredita da ctypes.Union. Maggiori informazioni al riguardo here.

Quindi si definiscono i campi unione nel membro della classe _fields_.

Problemi correlati