Python C API如何将结构数组从C传递给Python [英] Python C API How to pass array of structs from C to Python

查看:231
本文介绍了Python C API如何将结构数组从C传递给Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在创建的python模块,我想将这样的结构数组传递给python用户:

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;
};

我以为Py_BuildValues是我想要的功能.但似乎并非如此.在Python文档中,我发现 缓冲协议 .但是,这是我第一次开发python模块,而官方文档并没有太大帮助.

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.

缓冲协议是否是解决我的问题的最佳解决方案?如果是这样,如何将我的数组从C返回到python?

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

推荐答案

最后,我所做的是使用PyListObject创建一个列表对象,然后将要显示的结构值的字典添加到该列表中. python用户.

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; 

这篇关于Python C API如何将结构数组从C传递给Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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