简体   繁体   English

Python-如何检查弱引用是否仍然可用

[英]Python - how to check if weak reference is still available

I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... 我正在将一些弱引用从Python传递到C ++类中,但是当真实对象已经死亡时,C ++析构函数正在积极尝试访问ref,显然它崩溃了...

Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ? 是否有任何Python C / API方法可确定Python参考是否仍然有效,或者是否有其他已知的解决方法?

Thanks 谢谢

From Python C API documentation: Python C API文档中:

PyObject* PyWeakref_GetObject(PyObject *ref) PyObject * PyWeakref_GetObject(PyObject * ref)
Return value: Borrowed reference. 返回值:借用的参考。
Return the referenced object from a weak reference, ref. 从弱引用ref返回引用的对象。 If the referent is no longer live, returns None. 如果引用对象不再有效,则返回无。 New in version 2.2. 2.2版中的新功能。

If you call PyWeakref_GetObject on the weak reference it should return either Py_None or NULL, I forget which. 如果在弱引用上调用PyWeakref_GetObject,则它应该返回Py_None或NULL,我忘记了。 But you should check if it's returning one of those and that will tell you that the referenced object is no longer alive. 但是,您应该检查它是否返回其中之一,这将告诉您所引用的对象不再有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM