【问题标题】:Mixing ctypes and python classes in _fields_在 _fields_ 中混合 ctypes 和 python 类
【发布时间】:2020-07-30 13:36:08
【问题描述】:

我正在尝试为使用 gobject 的结构创建 ctypes 包装器。

结构体定义如下:

struct GstMetaStruc
{
    GstMeta meta;

    GstStructure* structure;
};

GstMeta 有一个现有的自省包装器,可以让我访问基本元对象。

我目前的错误方法如下所示:

import ctypes
import gi

gi.require_version("Gst", "1.0")

from gi.repository import Gst

class TcamMeta(ctypes.Structure):
    """

    """
    _fields_ = [("meta", Gst.Meta),
                ("structure", ctypes.POINTER(Gst.Structure))]

是否可以将 ctype 定义与现有的 python 包装类混合使用?
有没有更好的方法来为派生类型定义 python 类?

【问题讨论】:

    标签: python gstreamer ctypes gobject


    【解决方案1】:

    [Python 3.Docs]: ctypes - Structures and unions 声明(重点是我的):

    结构和联合必须派生自StructureUnion 基类,它们在ctypes 模块中定义。每个子类必须定义一个 _fields_ 属性。 _fields_ 必须是 2 元组 的列表,包含 字段名称字段类型

    字段类型必须是ctypes 类型,如c_int,或任何其他派生的ctypes 类型:结构、联合、数组、指针

    _fields_ 成员被实现为描述符,这意味着它们是“特殊的”(与常规类成员相比)。因此,在声明结构时会执行一些检查。

    >>> import ctypes as ct
    >>>
    >>> class A: pass
    ...
    >>> class Stru0(ct.Structure): pass
    ...
    >>> class Stru1(ct.Structure): _fields_ = [("c", Stru0)]
    ...
    >>> class Stru1(ct.Structure): _fields_ = [("c", ct.c_float)]
    ...
    >>> class Stru1(ct.Structure): _fields_ = [("c", int)]
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: second item in _fields_ tuple (index 0) must be a C type
    >>> class Stru1(ct.Structure): _fields_ = [("c", A)]
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: second item in _fields_ tuple (index 0) must be a C type
    

    所以,如果你没有得到 TypeError,你可能 OK。但简单看一下 PyGObject 示例,您不应该处于需要这样做的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-16
      • 2020-10-11
      • 2013-06-14
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多