我试图在ctypes中使用一个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代码:
#!/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')我错过了什么/做错了什么?
发布于 2014-02-02 22:35:23
函数返回指向结构的指针,而不是结构。
test.restype = ctypes.POINTER(custom_t)此外,还需要声明函数的参数:
lib.mmsh_connect.argtypes = [c_void_p, c_void_p, c_char_p, c_int]用法:
s = lib.mmsh_connect(None, None, 'Hello', 42)
print ctypes.c_value(s.contents.a)https://stackoverflow.com/questions/21517071
复制相似问题