Hi. I am trying to generate some structures using ctypes. The integer fields embedded in structures appear to get the wrong type when the structure is instantiated. It creates problems when I try to use the structures, since types are not as expected. I assume that I am doing something wrong, since this appears to be some basic functionality that doesn’t work. I have made the following code to demonstrate the problem:
I would expect the types of T1.a and T1.b to be ctypes.c_short and ctypes.c_long, like the individual variables a1 and b1. I have also tested with having ctypes-pointers in the structure, and they seem to get the correct type.
Could my installation be missing some component, or is this expected behavior?
What you’re seeing here is that ctypes’ automatic type conversion is taking effect. As far as I know, there are at least two instances where this occurs:
When accessing elements of composite data types (e.g., structure, union).
When processing a function’s return value.
If the type in question is a “simple” ctypes data type for which there is an “obvious” Python counterpart (e.g., c_long or c_char_p), the result is not the corresponding ctypes data type but the appropriate Python data type. For example, c_long becomes int and c_char_p becomes string.
However, these are just my observations (as a ctypes user).
Indeed, that’s documented in the ctypes reference here
Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types.
The reason for the difference in what type() returns for direct values and attributes defined in _fields_is due to the latter in effect being of type CField (a descriptor). That is the actual value that type(T1.a)sees is the value of the fields’ descriptor, after the conversion.
Thanks for the help. I had been looking in the documentation, but apparently not in the right place. I will try and use this information to get my code to work.