在不使用C函数的情况下更新ctypes python中结构指针的值

2024-06-14 12:57:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个C函数,它返回一个指向结构的指针:

struct iperf_test *
iperf_new_test()
{
    struct iperf_test *test;

    test = (struct iperf_test *) malloc(sizeof(struct iperf_test));
    ...
    return test;
}

此函数通过以下方式从Python调用:

^{pr2}$

该结构有一些值,例如:

struct iperf_test
{
    int       server_port;
    int       bind_port; 
};

我在互联网上看到的示例表明,我需要使用一个接收指针的函数来更改值,例如在python中:

self.lib.iperf_set_test_server_port(self._test, int(port))

在C中:

void
iperf_set_test_server_port(struct iperf_test *ipt, int srv_port)
{
    ipt->server_port = srv_port;
}

有没有方法可以不使用C函数直接更改值bind_端口?在


Tags: 函数testselfserverbindport结构struct
1条回答
网友
1楼 · 发布于 2024-06-14 12:57:19

是的。这就是为什么ctypes支持defining your own structs,并为函数定义原型。在

您需要对您的结构进行Python级别的定义,例如:

from ctypes import Structure, c_int, POINTER

class iperf_test(Structure):
    _fields_ = [("server_port", c_int),
                ("bind_port", c_int)]

然后,在调用C函数之前,set its ^{}正确:

^{pr2}$

现在您可以使用它by dereferencing(使用[0]完成,因为Python缺少*指针取消引用操作符),并直接在取消引用的结构上设置属性:

^{3}$

相关问题 更多 >