Hi.
Ich habe gerade festgestellt, dass ich völlig vergessen habe, Reference counts in meine Extension einzubauen und wundere mich über Memory leaks
Nun habe ich mir die Erklärung auf docs.python.org durchgelesen, verstehe aber nicht richtig, was es damit aufsich hat.
Muss ich Pointer, wie z.B. *self und *args auch mit einem Reference count belegen? Wo genau ist der Unterschied zu einem Increment Reference count und einem Decrement Refernce count? Muss ich diese _immer_ einsetzen, sobald ich mit einem PyObject* arbeite?
Bin dankbar für jegliche Art von Antworten und hoffe so, meine Memory leaks auszumerzen
Gruß und Danke!
[C API] Reference counts
Hallo.
Die entscheidenden Passagen sind
Die entscheidenden Passagen sind
undReference counts are always manipulated explicitly. The normal way is to use the macro Py_INCREF() to increment an object’s reference count by one, and Py_DECREF() to decrement it by one.
It is not necessary to increment an object’s reference count for every local variable that contains a pointer to an object. In theory, the object’s reference count goes up by one when the variable is made to point to it and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the end the reference count hasn’t changed. The only real reason to use the reference count is to prevent the object from being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the object that lives at least as long as our variable, there is no need to increment the reference count temporarily. An important situation where this arises is in objects that are passed as arguments to C functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to every argument for the duration of the call.
Das Leben ist wie ein Tennisball.
- birkenfeld
- Python-Forum Veteran
- Beiträge: 1603
- Registriert: Montag 20. März 2006, 15:29
- Wohnort: Die aufstrebende Universitätsstadt bei München
Es hilft bei diesem Thema auch sehr, sich existierenden C-Code anzuschauen, beispielsweise in Modulen der Python-Distribution (denn da ist das Reference-Counting mit sehr hoher Wahrscheinlichkeit korrekt; viele 3rd-party Extensions nehmen es auch nicht besonders genau mit den Referenzen).