10

I am writing a native function that will return multiple Python objects

PyObject *V = PyList_New(0);
PyObject *E = PyList_New(0);
PyObject *F = PyList_New(0);

return Py_BuildValue("ooo", V, E, F);

This compiles fine, however, when I call it from a Python program, I get an error:

SystemError: bad format char passed to Py_BuildValue

How can this be done correctly?

EDIT: The following works

PyObject *rslt = PyTuple_New(3);
PyTuple_SetItem(rslt, 0, V);
PyTuple_SetItem(rslt, 1, E);
PyTuple_SetItem(rslt, 2, F);
return rslt;

However, isn't there a shorter way to do this?

3
  • You also need to remember to decrement the reference count on V, E and F (Py_DECREF(V);, etc.) after calling Py_BuildValue, since Py_BuildValue increments the reference count of any object used with the O format specifier (see docs.python.org/c-api/arg.html#Py_BuildValue). Otherwise, the lists will never be freed, and you have a memory leak. Commented Aug 17, 2010 at 8:30
  • 1
    Thanks for the suggestion. I am returning Py_BuildValue("NNN", V, E, F) which does not increment the reference count. Commented Aug 17, 2010 at 23:04
  • I have a question when will V,E,F be free (equivalent Py_DECREF) after return to Python implementation? Thanks! Commented Feb 16, 2020 at 1:41

3 Answers 3

13

I think it wants upper-case O? "OOO", not "ooo".

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe you have also to add parenthesis to make python understand that you want to build a tuple : return Py_BuildValue("(OOO)", V, E, F);
2

As Ned Batcheder noted Py_BuildValue requires Uppercase and paranthesis to create the Tuple

Py_BuildValue("(OOO)", V, E, F);

Another option to achieve the same results is PyTuple_Pack

PyTuple_Pack(3, V, E, F);

Comments

-6

Use Cython.

return V, E, F

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.