4

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

3
  • When you say you want to transfer the PyObject * result into a C array, do you mean a C array of PyObject * or do you want to translate those array member objects into a more native C representation as well? Commented Feb 1, 2016 at 22:57
  • @KenClement I'd say probably as well. If I'm not mistaken I can use Pystring_fromstring to translate its member seperately. On the side note, when I do type(arr[3]) in python it tells me that it's unicode. Does that make any difference with string? Commented Feb 1, 2016 at 23:04
  • You are on the right track about using Pystring_fromstring but it does matter what version of Python you are using (2.7 or 3.5). (Also, I should probably ask if you are using CPython or IronPython or PyPy - I'm guessing from your remarks that its CPython) The difference between 2.7 and 3.5 will determine whether or not unicode makes a difference with str. In CPython 2.7 str generally deals with narrow character data - not unicode. In 3.5 that distinction has been erased (all strings are unicode). The AP{I's are not compatible in this regard. Which version are you on? Commented Feb 1, 2016 at 23:26

1 Answer 1

3

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.

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

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.