Releasing memory for objects returned in python via ctypes

I use ctypes to extend my c functions in MyDll in python.

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

further in the .py file I have a class whose methods call functions in MyDll via ctypes.

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

the corresponding function c MyTestClassInDLL_new is defined in MyDll as -

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

Note. I use new to instantiate this object in my vC ++ dll and return a pointer to it. I set the restype of this function in the .py file as ctypes.c_void_p.

The script I am running contains the following:

 testob = MyTestClass("5") 

this works great. testob, which I get here, is used later to call its methods, which internally call the c functions from MyDll.

However, the object was created using new in MyDll and returned via the MyTestClassInDLL_new () function. How to destroy this object? somewhere I need to use delete pTestObject to call its destructor, which clears the cleanup and the memory is freed.

+4
source share
1 answer

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

CPP:

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

N

 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) 
+3
source

All Articles