Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 322
Juster Avatar asked Nov 08 '12 16:11

Juster


People also ask

How do you use unions in Python?

Summary. The union of two or more sets returns distinct values from both sets. Use union() method or set union operator (|) to union two or more sets. The union() method accepts one or more iterables while the set union operator ( | ) only accepts sets.

How do you create a union list in Python?

To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .

How do you find the union B in Python?

Python Set union() method with examples The Set union() method returns a new set with the distinct elements from all the given Sets. The union is denoted by ∪ symbol. Lets say we have a Set A: {1, 2, 3} and Set B: {2, 3, 4} then to find the union of these sets we can call this method either like this A. union(B) or B.

How do you take the union of two arrays in Python?

To find union of two 1-dimensional arrays we can use function numpy. union1d() of Python Numpy library. It returns unique, sorted array with values that are in either of the two input arrays. Note The arrays given in input are flattened if they are not 1-dimensional.


1 Answers

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)]
like image 158
Adam Rosenfield Avatar answered Sep 19 '22 23:09

Adam Rosenfield