Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union-within-structure syntax in ctypes

Tags:

python

ctypes

Quick question about ctypes syntax, as documentation for Unions isn't clear for a beginner like me.

Say I want to implement an INPUT structure (see here):

typedef struct tagINPUT {
  DWORD type;
  union {
    MOUSEINPUT    mi;
    KEYBDINPUT    ki;
    HARDWAREINPUT hi;
  } ;
} INPUT, *PINPUT;

Should I or do I need to change the following code?

class INPUTTYPE(Union):
    _fields_ = [("mi", MOUSEINPUT),
                ("ki", KEYBDINPUT),
                ("hi", HARDWAREINPUT)]

class INPUT(Structure):
    _fields_ = [("type", DWORD),
                (INPUTTYPE)]

Not sure I can have an unnamed field for the union, but adding a name that isn't defined in the Win32API seems dangerous.

Thanks,

Mike

like image 259
MikeRand Avatar asked Aug 13 '10 19:08

MikeRand


1 Answers

Your Structure syntax isn't valid:

AttributeError: '_fields_' must be a sequence of pairs

I believe you want to use the anonymous attribute in your ctypes.Structure. It looks like the ctypes documentation creates a TYPEDESC structure (which is very similar in construction to the tagINPUT).

Also note that you'll have to define DWORD as a base type for your platform.

like image 125
Mark Avatar answered Oct 18 '22 18:10

Mark