如何检查Python中的对象是否是PyCapsule?

2024-05-28 17:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个C扩展,它接收和接受PyCapsule对象

在我的python包装器中,如何检查python对象是否为PyCapsule类型的对象

>>> # My C extension
>>> foo = Foo()
>>> capsule = foo.to_capsule()  # returns a PyCapsule object from the C extension
>>> capsule
<capsule object "foo" at 0xf707df08>
>>> type(capsule)
<class 'PyCapsule'>
isinstance(capsule, PyCapsule)
NameError: name 'PyCapsule' is not defined

我想写一个函数,比如:

def push_capsule(capsule):
    # check that the `capsule` is of type PyCapsule
    # c_extension.push_capsule(capsule)

Tags: theto对象类型objectfooismy
3条回答

正如您所指出的,PyCapsule类型不能直接从Python访问。要在没有严重的ctypes依赖性的情况下检测它(在DavidW接受的答案中),我将执行以下操作:

def is_capsule(o):
    t = type(o)
    return t.__module__ == 'builtins' and t.__name__ == 'PyCapsule'

这有点乱,但你可以从ctypes得到它:

def get_capsule_type():
    class PyTypeObject(ctypes.Structure):
        pass  # don't need to define the full structure
    capsuletype = PyTypeObject.in_dll(ctypes.pythonapi, "PyCapsule_Type")
    capsuletypepointer = ctypes.pointer(capsuletype)
    return ctypes.py_object.from_address(ctypes.addressof(capsulepointerpointer)).value

从地址创建py_object看起来需要一个包含PyObject*的地址,而不是PyObject*本身,因此需要额外的间接层

一般来说,首先检查您的API是否提供了某种方式来访问要引用的类

如果没有,则从虚拟实例恢复该类

PyCapsule = type(Foo().to_capsule())

...

if isinstance(bar, PyCapsule):
    ...

相关问题 更多 >

    热门问题