@@ -4725,22 +4725,23 @@ static struct PyModuleDef _cursesmodule = {
47254725 NULL
47264726};
47274727
4728+ static void
4729+ curses_destructor (PyObject * op )
4730+ {
4731+ void * ptr = PyCapsule_GetPointer (op , PyCurses_CAPSULE_NAME );
4732+ Py_DECREF (* (void * * )ptr );
4733+ PyMem_Free (ptr );
4734+ }
4735+
47284736PyMODINIT_FUNC
47294737PyInit__curses (void )
47304738{
47314739 PyObject * m , * d , * v , * c_api_object ;
4732- static void * PyCurses_API [PyCurses_API_pointers ];
47334740
47344741 /* Initialize object type */
47354742 if (PyType_Ready (& PyCursesWindow_Type ) < 0 )
47364743 return NULL ;
47374744
4738- /* Initialize the C API pointer array */
4739- PyCurses_API [0 ] = (void * )& PyCursesWindow_Type ;
4740- PyCurses_API [1 ] = (void * )func_PyCursesSetupTermCalled ;
4741- PyCurses_API [2 ] = (void * )func_PyCursesInitialised ;
4742- PyCurses_API [3 ] = (void * )func_PyCursesInitialisedColor ;
4743-
47444745 /* Create the module and add the functions */
47454746 m = PyModule_Create (& _cursesmodule );
47464747 if (m == NULL )
@@ -4752,9 +4753,29 @@ PyInit__curses(void)
47524753 return NULL ;
47534754 ModDict = d ; /* For PyCurses_InitScr to use later */
47544755
4756+ void * * PyCurses_API = PyMem_Calloc (PyCurses_API_pointers , sizeof (void * ));
4757+ if (PyCurses_API == NULL ) {
4758+ PyErr_NoMemory ();
4759+ return NULL ;
4760+ }
4761+ /* Initialize the C API pointer array */
4762+ PyCurses_API [0 ] = (void * )Py_NewRef (& PyCursesWindow_Type );
4763+ PyCurses_API [1 ] = (void * )func_PyCursesSetupTermCalled ;
4764+ PyCurses_API [2 ] = (void * )func_PyCursesInitialised ;
4765+ PyCurses_API [3 ] = (void * )func_PyCursesInitialisedColor ;
4766+
47554767 /* Add a capsule for the C API */
4756- c_api_object = PyCapsule_New (PyCurses_API , PyCurses_CAPSULE_NAME , NULL );
4757- PyDict_SetItemString (d , "_C_API" , c_api_object );
4768+ c_api_object = PyCapsule_New (PyCurses_API , PyCurses_CAPSULE_NAME ,
4769+ curses_destructor );
4770+ if (c_api_object == NULL ) {
4771+ Py_DECREF (PyCurses_API [0 ]);
4772+ PyMem_Free (PyCurses_API );
4773+ return NULL ;
4774+ }
4775+ if (PyDict_SetItemString (d , "_C_API" , c_api_object ) < 0 ) {
4776+ Py_DECREF (c_api_object );
4777+ return NULL ;
4778+ }
47584779 Py_DECREF (c_api_object );
47594780
47604781 /* For exception curses.error */
0 commit comments