为通过ctypes返回给python的对象分配内存 [英] deallocating memory for objects returned to python through ctypes

查看:166
本文介绍了为通过ctypes返回给python的对象分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ctypes将MyDll中的c函数扩展为python。

I am using ctypes for extending my c functions in MyDll to python.

from ctypes import cdll
libX = cdll.LoadLibrary("d:\\MyTestProject\\debug\\MyDll.dll")

在.py文件中我还有一个类

further in the .py file i have a class the methods of which call the functions in MyDll through ctypes.

Class MyTestClass:
       def __init__(self,id):
           libA.MyTestClassInDLL_new.restype = ctypes.c_void_p
           self.obj = libA.MyTestClassInDLL_new(id)

对应的c函数MyTestClassInDLL_new已在MyDll中定义为-

the corresponding c function MyTestClassInDLL_new has been defined in MyDll as -

extern "C" __declspec(dllexport) void * MyTestClassInDLL_new(char* id) 
{ 
     pTestObject = new CMyTestClassInDLL(CString(id)); 
     return (void *)pTestObject;    
}

注意,我正在使用new实例化我的vc ++ dll中的该对象并返回指向它的指针。我已在.py文件中将此函数的重新类型设置为ctypes.c_void_p。

Note I am using new to instantiate this object in my vc++ dll and returning the pointer to it. I have set the restype of this function in the .py file as ctypes.c_void_p.

我执行的脚本包含以下内容-

The script that I execute contains the following -

testob = MyTestClass("5")

这很好用。我在这里获得的testob进一步用于调用其从MyDll内部调用c函数的方法。

this works fine. the testob that i obtain here is used further to call its methods which internally call the c functions from MyDll.

但是,对象是使用MyDll中的new创建的,并通过MyTestClassInDLL_new返回()功能。该物体如何被销毁?在某个地方,我需要使用delete pTestObject,以便调用其析构函数进行清理并释放内存。

However the object was created using new in MyDll and returned through MyTestClassInDLL_new() function. How is this object to be destroyed ? somewhere i need to use delete pTestObject so that its destructor is called which does the cleanup and the memory is deallocated.

推荐答案

我通常通过添加一个extern destroy对象函数来处理此问题,该函数可以将指针传递回并删除它。

I typically handle this by adding an extern destroy object function that I can pass the pointer back to and delete it.

CPP:

SomeClass* createObj()
{
    return new SomeClass();
}

void destroyObj(SomeClass* pObj){
  delete pObj;
  pObj = NULL;
}

H:

extern "C" {
  SomeClass* createObj();
  void destroyObj(SomeClass*);
}

PY:

class SomeObj:
    def __init__(self):
        self.soLib = cdll.LoadLibrary(PATH_SO)
        _createObj = self.soLib.createObj
        _createObj.restype = POINTER(c_long)

        self._objRef = _createObj()
        ## do stuff with self._objRef

    def __del__(self):
        self.soLib.destroyObj(self._objRef)

这篇关于为通过ctypes返回给python的对象分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆