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!
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.