2012-11-08 220 views
9

私はPythonで作業を始めました。私はどのように(ctypesを使って)Pythonで共用体を定義すべきなのでしょうか?うまくいけば、組合はctypesを使ってサポートされているのは間違いないでしょう。次のCコードは、pythonで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をどのように例えば、簡単な例は、他の誰かが単にctypes.Unionから継承するクラスを作成するのと同じ答え

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 

答えて

5

ctypes tutorialをご覧ください。 ctypes.Unionクラスを使用します。

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

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

おかげさまで、私はそのctypes情報をもっと慎重に読むべきです:) – Juster

2

を探している場合は追加しました。 詳しくはhereをご覧ください。

次に、_fields_クラスメンバの結合フィールドを定義します。

関連する問題