Python C API How to pass array of structs from C to Python

允我心安 提交于 2019-12-03 17:30:57

问题


For a python module I'm creating, I want to pass to the python user an array of structs like this:

struct tcpstat
{
    inet_prefix local;
    inet_prefix remote;
    int     lport;
    int     rport;
    int     state;
    int     rq, wq;
    int     timer;
    int     timeout;
    int     retrs;
    unsigned    ino;
    int     probes;
    unsigned    uid;
    int     refcnt;
    unsigned long long sk;
    int     rto, ato, qack, cwnd, ssthresh;
};

I thought that Py_BuildValues was the function I was looking for. But seems like it isn't. Looking in the Python documentation I found the Buffer Protocol. But is the first time I'm developing a python module and the official documentation didn't help me much.

Is the Buffer Protocol the best solution for my problem? If so, How could I return my array from C to python?


回答1:


Finnally what I did was make a list Object with PyListObject and append to that list a dictionary with the values of the struct that I want to show to the python user.

Hope this will help someone with the same doubt, here is the code:

PyObject *dict = NULL;
PyListObject *list;

list = (PyListObject *) Py_BuildValue("[]");

int i = 0;
for (i; i < stats_length; i++) {
    dict = Py_BuildValue("{s:i}", "LPort", stats[i].lport);
    PyList_Append(list, dict);
}

return (PyObject *) list; 


来源:https://stackoverflow.com/questions/15786525/python-c-api-how-to-pass-array-of-structs-from-c-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!