Search code examples
pythonunionctypes

how to use unions with python?


I have just started to working with python and i'm wondering how should i define unions with python (using ctypes)? Hopefully i'm right that unions are supported via ctypes. For example how the following c code is in 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,Simple example added if someone else is looking the same answer

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

Solution

  • Take a look at the ctypes tutorial. You use the ctypes.Union class:

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