From 95f087cd0b261ce4dc0f8b8e4d55ca5d1b1f6dec Mon Sep 17 00:00:00 2001 From: Spike Date: Mon, 13 Mar 2023 22:54:47 -0600 Subject: [PATCH] Fix reference counting errors in registerNewType --- modules/python/src2/cv2.cpp | 1 + modules/python/src2/pycompat.hpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index 5d952412f3..3f976c9a81 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -284,6 +284,7 @@ static bool init_submodule(PyObject * root, const char * name, PyMethodDef * met static inline bool registerTypeInModuleScope(PyObject* module, const char* type_name, PyObject* type_obj) { + Py_INCREF(type_obj); /// Give PyModule_AddObject a reference to steal. if (PyModule_AddObject(module, type_name, type_obj) < 0) { PyErr_Format(PyExc_ImportError, diff --git a/modules/python/src2/pycompat.hpp b/modules/python/src2/pycompat.hpp index ceaee06f49..bd3956dbc0 100644 --- a/modules/python/src2/pycompat.hpp +++ b/modules/python/src2/pycompat.hpp @@ -338,8 +338,10 @@ PyObject* pyopencv_from(const TYPE& src) if (!registerNewType(m, #EXPORT_NAME, (PyObject*)pyopencv_##CLASS_ID##_TypePtr, SCOPE)) \ { \ printf("Failed to register a new type: " #EXPORT_NAME ", base (" #BASE ") in " SCOPE " \n"); \ + Py_DECREF(pyopencv_##CLASS_ID##_TypePtr); \ ERROR_HANDLER; \ } \ + Py_DECREF(pyopencv_##CLASS_ID##_TypePtr); \ } // Debug module load: