Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!