Python C Api将PyObject *转移到c数组中 [英] Python C Api transfer a PyObject * into c array

查看:110
本文介绍了Python C Api将PyObject *转移到c数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python c api并希望从python返回数组.我从python端返回了一个python数组,并希望将PyObject *结果转移到c数组中,以便我可以使用它.

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.

反正我能做到吗?

侧面问题:在什么情况下试图返回数组中的元素,如

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

return arr[3]

会导致PyObject_callobject返回NULL吗?

will cause the PyObject_callobject return NULL?

return arr

给我一​​些东西

推荐答案

在Python中,数组"是 list 数据类型.查看C API中的 PyList _ * 函数.您可以在此处为2.7

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)获取列表成员的数量和 PyObject * PyList_GetItem(PyObject *列表,Py_ssize_t索引),以获取对该索引处成员的引用.

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.

简单使用 malloc 或类似的分配器和 for 循环即可解决问题.

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

还请注意,仅涉及借用的引用,因此不会通过 void Py_INCREF(PyObject * o) void Py_DECREF(PyObject * o)来维护这些对象的引用计数是必需的.

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.

这篇关于Python C Api将PyObject *转移到c数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆