首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python :使用restype时传递的参数为空

Python :使用restype时传递的参数为空
EN

Stack Overflow用户
提问于 2014-02-02 22:25:28
回答 1查看 534关注 0票数 1

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

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

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

我(很明显)尝试过添加argtypes,使用不同的数据类型,等等,但都没有效果。

一些简单的示例代码演示了这个问题:

C图书馆:

代码语言:javascript
复制
// 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代码:

代码语言:javascript
复制
#!/usr/bin/env python3
# Python2 give the same results

import ctypes

class custom_t(ctypes.Structure):
    _fields_ = [
        ('a', ctypes.c_int),
        ('b', ctypes.c_int),
        ('c', ctypes.c_int),
        ('d', ctypes.c_int),
        ('e', ctypes.c_int),
    ]

lib = ctypes.cdll.LoadLibrary('./test.so');
test = lib.mmsh_connect
test.restype = custom_t # <- Oh woe is this line!

test(None, None, b'Hello', 42)
#test(42, b'Hello')
#test(b'Hello')

我错过了什么/做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-02 22:35:23

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

代码语言:javascript
复制
test.restype = ctypes.POINTER(custom_t)

此外,还需要声明函数的参数:

代码语言:javascript
复制
lib.mmsh_connect.argtypes = [c_void_p, c_void_p, c_char_p, c_int]

用法:

代码语言:javascript
复制
s = lib.mmsh_connect(None, None, 'Hello', 42)
print ctypes.c_value(s.contents.a)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21517071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档