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

标签 python constructor ctypes init

我有以下代码:

class MyStruct(ctypes.Structure):
      _fields_= [('id', ctypes.uint),
                 ('perm', ctypes.uint)]

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

ms = MyStruct.from_buffer_copy("\xAA\xAA\xAA\xAA\x11\x11\x11\x11")
print ms.id, ms.perm

一切正常,这里的 id 将是 0xAAAAAAAA 并且 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

但是我的代码通过以下语句引发错误:

AttributeError: 'MyStruct' object has no attribute 'from_buffer_copy'

经过一些研究,我发现 from_buffer_copy 是一个 ctypes._CData 方法。在文档中我们可以读到 _CData 类是 non-public class .

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

预先感谢您的回复 问候

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

最佳答案

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

一个简单的解决方案就是继续使用 MyStruct.from_buffer_copy 或编写另一个工厂函数来满足您的需要。如果您坚持使用 MyStruct(buffer),那么您可以使用 __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

关于python - 在继承的 ctypes.Structure 类的构造函数中调用 from_buffer_copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11485496/

相关文章:

java - 对java构造函数感到困惑

c++ - C++ 构造函数是否称为预初始化?

python ctypes加载dll返回新的malloc'd缓冲区

python - 如何删除 python-igraph 中的边缘属性

iphone - 在我的 iPhone 的 Python 解释器上安装 Python Imaging Library

python - 无法获取 POST 参数

python - 合并两个不同形状的 Pandas 数据框时出现问题?

c++ - 在 C++ 中,是否可以在构造函数中访问静态变量?

python - 通过 Ctypes 从 C 到 Python - 将函数指针的结构包装到静态函数

python - 在 Windows : function not found 上使用 ctypes 在 python 中包装 c++ 函数