小编Blu*_*luz的帖子

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

我有以下代码:

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变量有很多参数.

python constructor ctypes init

2
推荐指数
1
解决办法
3004
查看次数

标签 统计

constructor ×1

ctypes ×1

init ×1

python ×1