Hongjun Han
Hongjun Han

Reputation: 65

Python C Api transfer a PyObject * into c array

I used python c api and wish to get an array back from python. I returned a python array from the python side and want to transfer the PyObject* result into a c array so I can use it.

Is there anyway I can do that?

Side questions: In what circumstance trying to return an element in the array like

return arr[3]

will cause the PyObject_callobject return NULL?

return arr

does give me something

Upvotes: 4

Views: 5070

Answers (1)

Ken Clement
Ken Clement

Reputation: 768

In Python an "array" is a list datatype. Look at the PyList_* functions in the C API. You can find this reference here for 2.7 and here for 3.5. The functions of interest are:

Py_ssize_t PyList_Size(PyObject *list) to get the number of list members and PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index) to get a reference to the member at that index.

A simple use of malloc or similar allocator and a for loop should do the trick.

Also note that only borrowed references are involved, so no reference count maintenance of these objects via void Py_INCREF(PyObject *o) and void Py_DECREF(PyObject *o) is necessary.

Upvotes: 3

Related Questions