Search code examples
pythonarraysinitializationstructurectypes

How can I initialize this ctypes Structure array?


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?


Solution

  • 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:

    object.__repr__(self)

    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.

    object.__str__(self)

    Called by str(object) and the built-in functions format() and print() 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 calls object.__repr__().