python - 在 _fields_ 中混合 ctypes 和 python 类

标签 python gstreamer ctypes gobject

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

结构定义如下:

struct GstMetaStruc
{
    GstMeta meta;

    GstStructure* structure;
};

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

我目前的错误做法是这样的:

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 3.Docs]: ctypes - Structures and unions状态(强调是我的):

Structures and unions must derive from the Structure and Union base classes which are defined in the ctypes module. Each subclass must define a _fields_ attribute. _fields_ must be a list of 2-tuples, containing a field name and a field type.

The field type must be a ctypes type like c_int, or any other derived ctypes type: structure, union, array, pointer.

_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 示例,您不应该遇到需要这样做的情况。

关于python - 在 _fields_ 中混合 ctypes 和 python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61265051/

相关文章:

ffmpeg - GStreamer 中的 fdsink 元素不能用于将正确的字节流输出到管道

Python ctypes 不在 Mac OS X 上加载动态库

python - 如何使用 ctypes 多次 recv_into C 缓冲区?

python - 使用 add_cookie 时 WebDrive 出现奇怪的异常

python - 替换 python 数据框中的值

python - 选择性 Numpy 数组操作(取决于值)

python - 如何在 Pandas 中的另一个词之前提取一个词

c++ - 如何修复 GLib-GObject-WARNING ** : cannot register existing type `gchar'

python - 以编程方式并排合并两个视频

Python ctypes返回一个函数指针数组