Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Can we convert a ctypes structure to a dictionary?

Tags:

python

ctypes

I have a ctypes structure.

class S1 (ctypes.Structure):
    _fields_ = [
    ('A',     ctypes.c_uint16 * 10),
    ('B',     ctypes.c_uint32),
    ('C',     ctypes.c_uint32) ]

if I have X=S1(), I would like to return a dictionary out of this object: Example, if I do something like: Y = X.getdict() or Y = getdict(X), then Y might look like:

{ 'A': [1,2,3,4,5,6,7,8,9,0], 
  'B': 56,
  'C': 8986 }

Any help ?

like image 579
G.A. Avatar asked Sep 24 '10 17:09

G.A.


People also ask

Can list be convert to dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

What does Ctypes do in Python?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Can dictionary be converted to tuple?

A dictionary is defined and is displayed on the console. The tuple is converted to a list, and the dictionary is added to it using the 'append' method. Then, this resultant data is converted to a tuple.

Can a dictionary be converted into a string?

Use the str() and the literal_eval() Function From the ast Library to Convert a Dictionary to a String and Back in Python. This method can be used if the dictionary's length is not too big. The str() method of Python is used to convert a dictionary to its string representation.


1 Answers

Probably something like this:

def getdict(struct):
    return dict((field, getattr(struct, field)) for field, _ in struct._fields_)

>>> x = S1()
>>> getdict(x)
{'A': <__main__.c_ushort_Array_10 object at 0x100490680>, 'C': 0L, 'B': 0L}

As you can see, it works with numbers but it doesn't work as nicely with arrays -- you will have to take care of converting arrays to lists yourself. A more sophisticated version that tries to convert arrays is as follows:

def getdict(struct):
    result = {}
    for field, _ in struct._fields_:
         value = getattr(struct, field)
         # if the type is not a primitive and it evaluates to False ...
         if (type(value) not in [int, long, float, bool]) and not bool(value):
             # it's a null pointer
             value = None
         elif hasattr(value, "_length_") and hasattr(value, "_type_"):
             # Probably an array
             value = list(value)
         elif hasattr(value, "_fields_"):
             # Probably another struct
             value = getdict(value)
         result[field] = value
    return result

If you have numpy and want to be able to handle multidimensional C arrays, you should add import numpy as np and change:

 value = list(value)

to:

 value = np.ctypeslib.as_array(value).tolist()

This will give you a nested list.

like image 161
Tamás Avatar answered Oct 23 '22 10:10

Tamás