Python的CTypes垃圾回收

2024-04-19 20:30:13 发布

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

我使用ctypes从python访问c库(实际上是c++代码):

class CRMeAnnotationList(object):
def __init__(self):
    self.obj = lib.CRMeAnnotationList_new()de
def __del__(self):
    if self.obj:
        lib.CRMeAnnotationList_destroy(self.obj)
lst = CRMeAnnotationList()

C代码看起来像这样

^{pr2}$

这个密码给了我 结束,退出代码为-1073741819(0xc000005)

如果我不销毁指针,我得到0作为退出代码。在

这是否意味着我不需要销毁该指针,即在python代码中执行析构函数部分del?在


Tags: 代码selfobjnewifobjectinitlib
1条回答
网友
1楼 · 发布于 2024-04-19 20:30:13

您可能正在运行64位Python并且没有正确设置.argtypes和{}。在

示例:

测试.cpp

#define API __declspec(dllexport) // Windows-specific

extern "C" {

struct CRMeAnnotationList {
    int a;
};

API CRMeAnnotationList* CRMeAnnotationList_new() {
    return new CRMeAnnotationList();
}

API void CRMeAnnotationList_destroy(CRMeAnnotationList* p) {
    if(p)
        delete p;
}

}

测试.py

^{pr2}$

输出:

created   0x2232dfc35c0
destroyed 0x2232dfc35c0

.argtypes.restype行被注释掉时的输出:

created   0x1c98e8f35c0
destroyed 0x1c98e8f35c0
Exception ignored in: <function CRMeAnnotationList.__del__ at 0x000001C98E9176A8>
Traceback (most recent call last):
  File "C:\Users\metolone\Desktop\test.py", line 16, in __del__
OSError: exception: access violation reading 0xFFFFFFFF8C6CABCF

注意访问冲突的地址。它是一个扩展到64位的32位值符号。在

相关问题 更多 >