Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda