调整ctypes结构的大小

时间:2016-10-25 22:56:06

标签: python ctypes

我需要动态调整ctypes结构字段的大小:

from ctypes import *

class a(Structure):
    _fields_ = [('first', c_ubyte*10), ('second', c_ubyte*20)]

现在让我们说我需要第二个'是100个字节而不是20个。我尝试了以下内容:

class b(a):
    _fields_ = [('second', c_ubyte*100)]

这似乎有效:

b.second
<Field type=c_ubyte_Array_100, ofs=30, size=100>

问题在于它所做的一切都是将100元素数组添加到b的末尾:

sizeof(b) #want this to be 110
130

c = b()
addressof(c.second) - addressof(c) #want this to be 10
30

那么我怎样才能延长第二个&#39; b的成员没有完全重新定义它作为与a无关的类。

此外,像调整大小的解决方案不起作用:

c = a()
resize(c.second, 100)
ValueError: Memory cannot be resized because this object doesn't own it

1 个答案:

答案 0 :(得分:0)

没有一种简单的方法可以做到这一点因为ctypes结构是相当静态的(以匹配它们的c-对应物)。无论如何,你可以继承ctypes.Structure并做这样的事情作为该类的一个函数:

def getUpdated(self, fieldName, fieldType):
    fieldsCopy = self._fields_
    found = False
    for idx, itm in enumerate(fieldsCopy):
        # find a matching field name

        i = list(itm) # can't modify a tuple
        if i[0] == fieldName:
            i[1] = fieldType
            fieldsCopy[idx] = tuple(i) # update the type with the new one
            found = True
            break # end the loop

    if not found: # fieldName wasn't in the field
        return False

    class TmpStructure(Structure):
        ''' we made a new structure type based off the original '''
        _pack_ = self._pack_
        _fields_ = fieldsCopy

    return TmpStructure # return the type, though we could probably 
                        # pass the values if needed and make a new instance
                        # of the new 

`

基本上,我们返回一个更改字段类型的新类型。这可以修改为还处理位域,Structure继承和/或返回实例而不是类型。虽然这应该足以让你开始。