我正在尝试为 linphone 库编写 Cython 包装器,但我面临一个问题:我想在 C 对象中存储表示我的 C 对象的 Python 对象的弱引用。
这是我的包装器:
cdef void on_global_state_changed_cbs(LinphoneCore *lc, LinphoneGlobalState gstate, const char *message):
print('Internal Callback : ' + str(gstate) + ' : ' + message)
cbs = linphone_core_get_current_callbacks(lc)
callbacks = CoreCallbacks.from_ptr(cbs)
if callbacks.global_state_cb is not None:
core = Core.from_ptr(lc)
callbacks.global_state_cb(core, gstate, message)
ctypedef struct LinphoneCoreCbs:
pass
cdef class CoreCallbacks:
cdef object __weakref__
cdef LinphoneCoreCbs *ptr
cpdef global_state_cb
@staticmethod
cdef CoreCallbacks from_ptr(LinphoneCoreCbs *_ptr, take_ref = True):
cdef CoreCallbacks coreCbs
user_data = belle_sip_object_data_get(<belle_sip_object_t *>_ptr, 'python_user_data')
if user_data is not NULL:
tmpWRef = <object>user_data
print tmpWRef
coreCbs = tmpWRef()
if coreCbs is None:
coreCbs = CoreCallbacks.__new__(CoreCallbacks)
coreCbs.ptr = linphone_core_cbs_ref(_ptr) if take_ref else _ptr
else:
coreCbs = CoreCallbacks.__new__(CoreCallbacks)
coreCbs.ptr = linphone_core_cbs_ref(_ptr) if take_ref else _ptr
print coreCbs
wref = weakref.ref(coreCbs)
print wref
belle_sip_object_data_set(<belle_sip_object_t *>_ptr, 'python_user_data', <void *>wref, NULL)
linphone_core_cbs_set_global_state_changed(coreCbs.ptr, &on_global_state_changed_cbs)
return coreCbs
def __dealloc__(self):
print 'Dealloc ' + str(self)
if self.ptr is not NULL:
belle_sip_object_data_remove(<belle_sip_object_t *>self.ptr, 'python_user_data')
linphone_core_cbs_unref(self.ptr)
self.ptr = NULL
问题是当我从回调中调用 Core.from_ptr 时,tmpWRef 表示该对象已死,因此创建了一个新对象。我在dealloc方法中添加了一个打印,我看到对象还没有被释放。
Smart猫小萌
相关分类