Python ctypes:使用restyp时传递的参数为null

2024-09-27 19:30:43 发布

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

我正在尝试使用一个C库(libmms,尽管这并不重要);我首先编写了一个可以工作的小型C程序,但是我似乎很难让它与ctypes一起工作

每当我使用test.restype = custom_t指定返回类型(这是必需的,因为我以后需要它),事情就开始中断。在

我的参数(url)似乎不起作用,或者工作非常奇怪(参见C文件中的注释)。如果我将结构简化为一个条目(int a),那么一切都如预期的那样工作!(它在大约3到4行处断开,libmms中的原始结构要大得多)。在

我(显然)尝试过添加argtypes,处理各种数据类型,等等,但都没有用。。。在

一些简单的示例代码来演示问题:

C库:

// Compiled with: clang -shared -Wl,-soname,test -o test.so -fPIC test.c
// Also tried gcc, with the same results
#include <stdio.h>

struct mmsh_t {
    int a;
    int b;
    int c;
    int d;
    int e;
};

// Called as: test(None, None, b'Hello', 42)
// Outputs: mmsh_connect: (null)
struct mmsh_t *mmsh_connect (void *io, void *data, const char *url, int bandwidth) {

// Called as: test(42, b'Hello')
// Segfaults
// Curiously, when I output this with the Python code:
// test(b'Hello')
// It outputs:  mmsh_connect: Hello
// Which is what I expected!
//struct mmsh_t *mmsh_connect (int io, const char *url) {

// Called as: test(b'Hello')
// Outputs: mmsh_connect: 
//struct mmsh_t *mmsh_connect (const char *url) {
    struct mmsh_t *this;
    printf("mmsh_connect: %s\n", url);
    return this;
}

Python代码:

^{pr2}$

我遗漏了什么/做错了什么?在


Tags: testurlhelloasconnectwiththis结构
1条回答
网友
1楼 · 发布于 2024-09-27 19:30:43

函数返回指向结构的指针,而不是结构。在

test.restype = ctypes.POINTER(custom_t)

还需要声明函数的参数:

^{pr2}$

用法:

s = lib.mmsh_connect(None, None, 'Hello', 42)
print ctypes.c_value(s.contents.a)

相关问题 更多 >

    热门问题