在继承的ctypes.Structure类的构造函数中调用from_buffer_copy

Blu*_*luz 2 python constructor ctypes init

我有以下代码:

class MyStruct(ctypes.Structure):
      _fields_= [('id', ctypes.uint),
                 ('perm', ctypes.uint)]
Run Code Online (Sandbox Code Playgroud)

定义类后,我可以直接在我的字段上复制缓冲区中的数据.例如:

ms = MyStruct.from_buffer_copy("\xAA\xAA\xAA\xAA\x11\x11\x11\x11")
print ms.id, ms.perm
Run Code Online (Sandbox Code Playgroud)

Everythings工作正常,这里id0xAAAAAAAA,perm等于0x11111111.

现在,我试图在实例化过程中做同样的事情,使用以下代码:

class MyStruct(ctypes.Structure):
      _fields_= [('id', ctypes.uint),
                 ('perm', ctypes.uint)]
      def __init__(self):
          super(MyStruct, self).__init__()
          self.from_buffer_copy("\xAA\xAA\xAA\xAA\x11\x11\x11\x11")

ms = MyStruct()
print ms.id, ms.perm
Run Code Online (Sandbox Code Playgroud)

但我的代码使用以下语句引发错误:

AttributeError:'MyStruct'对象没有属性'from_buffer_copy'

经过一番研究,我发现这from_buffer_copy是一种ctypes._CData方法.在文档中我们可以读到_CData该类是非公共类.

所以这是我的问题.我想from_buffer_copy在构造函数中使用,但此时它看起来"不可调用".你可以帮帮我吗 ?

在此先感谢您的回复问候

PS:我不想使用这个样式,super(MyStruct,self).__init__(id=0x44444444,perm=0x11111111)因为在我的真实代码中我的fields变量有很多参数.

Luk*_*uke 8

问题是from_buffer_copy 从给定的缓冲区创建新的 Structure实例.当你在__init__中使用它时,结构已经被创建,因此无法使用from_buffer_copy(这就是为什么它只能作为类方法而不是实例方法使用).

一个简单的解决方案就是继续使用MyStruct.from_buffer_copy或编写另一个工厂函数以满足您的需求.如果您坚持使用MyStruct(缓冲区),那么您可以使用__new__来实现此目的,因为它是创建实例之前调用的:

import ctypes
class MyStruct(ctypes.Structure):
    _fields_= [('id', ctypes.c_uint),('perm', ctypes.c_uint)]
    def __new__(cls, buf):
        return cls.from_buffer_copy(buf)

    def __init__(self, data):
        pass  ## data is already present in class

ms = MyStruct("\xAA\xAA\xAA\xAA\x11\x11\x11\x11")
print ms.id, ms.perm
Run Code Online (Sandbox Code Playgroud)