I have a structure defined using class
type and I want to initialize test_arr
like this:
from ctypes import *
class ST_DATA(Structure):
_fields_ = [("test1", c_int),
("test2", c_double),
("test_arr", c_double*2)]
stmyData = ST_DATA(1, 2, (3, 4))
print(stmyData.test1, stmyData.test2, stmyData.test_arr)
Result:
1 2.0 <__main__.c_double_Array_2 object at 0x11BB2AD8>
I don't understand this situation. How can I initialize this structure array in Python?
It is initialized, but the default print representation doesn't reflect the data...just the object's type and address.
It's a good habit to write a debug representation for classes so printing a class instance is more convenient. In this case, ctypes
arrays can be converted to lists to see their content:
from ctypes import *
class ST_DATA(Structure):
_fields_ = [('test1', c_int),
('test2', c_double),
('test_arr', c_double * 2)]
# debug representation "magic" method
def __repr__(self):
return f'ST_DATA(test1={self.test1}, test2={self.test2}, test_arr={list(self.test_arr)})'
stmyData = ST_DATA(1, 2, (3, 4))
print(stmyData)
Output:
ST_DATA(test1=1, test2=2.0, test_arr=[3.0, 4.0])
See also:
Called by the
repr()
built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form<...some useful description...>
should be returned. The return value must be a string object. If a class defines__repr__()
but not__str__()
, then__repr__()
is also used when an “informal” string representation of instances of that class is required.This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
Called by
str(object)
and the built-in functionsformat()
andprint()
to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.This method differs from
object.__repr__()
in that there is no expectation that__str__()
return a valid Python expression: a more convenient or concise representation can be used.The default implementation defined by the built-in type
object
callsobject.__repr__()
.