Python CFFI Converts Structure to Dictionary

There is a way to initialize a structure with a dictionary:

fooData= {'y': 1, 'x': 2}
fooStruct = ffi.new("foo_t*", fooData)
fooBuffer = ffi.buffer(fooStruct)

Is there any ready-made function for conversion?

fooStruct = ffi.new("foo_t*")
(ffi.buffer(fooStruct))[:] = fooBuffer
fooData= convert_to_python( fooStruct[0] )    

Do I need to use the ffi.typeof ("foo_t") fields.

I still use this code:

def __convert_struct_field( s, fields ):
    for field,fieldtype in fields:
        if fieldtype.type.kind == 'primitive':
            yield (field,getattr( s, field ))
        else:
            yield (field, convert_to_python( getattr( s, field ) ))

def convert_to_python(s):
    type=ffi.typeof(s)
    if type.kind == 'struct':
        return dict(__convert_struct_field( s, type.fields ) )
    elif type.kind == 'array':
        if type.item.kind == 'primitive':
            return [ s[i] for i in range(type.length) ]
        else:
            return [ convert_to_python(s[i]) for i in range(type.length) ]
    elif type.kind == 'primitive':
        return int(s)

Is there a faster way?

+4
source share
1 answer

Your code is ok.

CFFI , , . , ffi.new("foo_t*", {'p': p1}), p1 - cdata, , . : , "", cdata, .

0

All Articles