Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
Is it necessary to release some resources allocated by the Python C API

I have the following C code that calls the Python API library:

PyObject *obj;

PyObject *arguments;

arguments = PyTuple_New(2);

PyTuple_SetItem(arguments, 0, PyLong_FromLongLong(10));

PyTuple_SetItem(arguments, 1, PyLong_FromLongLong(20));

obj = PyObject_CallObject(my_function, arguments); // should "obj" be released after being used?

PyLong_AsLongLong(obj);

Py_DECREF(arguments); // is this instruction necessary?

I have two questions (both are in the code as comments), namely: 1) should the variable obj be released after being used (if yes, how is this done?) and 2) do we need to decrease the reference counter of variable arguments (i.e. do we need Py_DECREF(arguments);)? Thanks for all the help in advance!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You should read https://docs.python.org/3/c-api/intro.html#objects-types-and-reference-counts, which describes the correct way to handle reference counting with the Python C API. Following the rules described there, the correct code for your situation would be the following.

PyObject *obj;
PyObject *arguments;
arguments = PyTuple_New(2);  // this returns a new reference

// You don't need to Py_DECREF() the return values of PyLong_FromLongLong()
// because PyTuple_SetItem() steals a reference. 
PyTuple_SetItem(arguments, 0, PyLong_FromLongLong(10));
PyTuple_SetItem(arguments, 1, PyLong_FromLongLong(20));

obj = PyObject_CallObject(my_function, arguments); // this returns a new reference

PyLong_AsLongLong(obj);

Py_DECREF(arguments); // this is necessary because a new reference was created earlier
Py_DECREF(obj); // this is necessary because a new reference was created earlier

Note that I have not added any error checks. Some of these functions can return NULL on error, so it would be wise to check for them.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda