Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes c_float.value doesn't return value

Tags:

python

ctypes

I'm working on a Python script that is intended to print all values from a structure, along with the value names. The values in the structure are all ctypes, but I'm having trouble printing them. As it stands, when I run the following code

import ctypes

class test(ctypes.Structure):
    pass
test._fields_ = [
    ('a', ctypes.c_float),
    ('b', ctypes.c_float),
    ('c', ctypes.c_float)]

d = test(1, 2, 3)

for field in d._fields_:
    print field[0], field[1].value

I get

a <attribute 'value' of '_ctypes._SimpleCData' objects>
b <attribute 'value' of '_ctypes._SimpleCData' objects>
c <attribute 'value' of '_ctypes._SimpleCData' objects>

Any thoughts? I thought .value was supposed to get the value from a ctypes object, but it doesn't seem to want to...

Thanks!

like image 494
ryantmer Avatar asked Aug 15 '26 11:08

ryantmer


1 Answers

_fields_ has the field names and data types. You want the names, and for the values use built-in getattr:

>>> for name, dtype in d._fields_:
...     print name, getattr(d, name)
... 
a 1.0
b 2.0
c 3.0
like image 98
Eryk Sun Avatar answered Aug 18 '26 02:08

Eryk Sun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!