我有一个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)
通常,首先检查您的API是否提供某种方式来访问您要引用的类。
如果没有,请从虚拟实例中恢复该类。
PyCapsule = type(Foo().to_capsule())
...
if isinstance(bar, 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*
本身,因此需要间接层。