c python 传参数 数组_Python C API如何将结构数组从C传递给Python

1586010002-jmsa.png

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?

解决方案

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值