I'm wondering how to cope with the following problem. Inside my C++ class I have an auxiliary PyObject pointer.
class Foo
{
public:
// Should I new the dictionary here in constructor?
Foo()
{
}
// Must decrease the reference count or explicitly delete the dictionary?
~Foo()
{
Py_DECREF(myDictionary);
}
void sync()
{
myDictionary = PyDict_New();
for (int i=0; i<myInternalData.size(); i++)
{
PyObject *key = PyInt_FromLong(i);
PyObject *val = PyInt_FromLong(myInternalData.at(i));
PyDict_SetItem(dict,key,val);
Py_DecRef(key);
Py_DecRef(val);
}
}
private:
PyObject *myDictionary;
std::vector<int> myInternalData;
}
In my C++ code the myInternalData structure is occasionally updated or resized and I want to know how to cope with the proper memory allocation of my python dictionary.
I don't know how to deallocate the memory associated with it, or how to correctly keep it synchronized with my internal std::vector without corrupting the heap or provoking memory leaks.
Some helps with Python C API? Should I deallocate the PyDict with PyObject_Del and then reallocating it again? Someone suggesting another approach?
syncfrequently? From what I can understand this is a possible source of memory leaks, since you are allocating new objects. Also (I might be wrong here), I think that probably the appropriate way to deallocate the dictionary is to decrease the ref counter to zero (docs.python.org/2/c-api/refcounting.html). Did you try using valgrind to see where you are getting mem-leaks?