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

问题描述 投票:1回答:2

我有一个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)
python python-3.x python-c-api
2个回答
2
投票

通常,首先检查您的API是否提供某种方式来访问您要引用的类。

如果没有,请从虚拟实例中恢复该类。

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

...

if isinstance(bar, PyCapsule):
    ...

0
投票

有点混乱,但是您可以从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*本身,因此需要间接层。

© www.soinside.com 2019 - 2024. All rights reserved.