我在 Kubuntu Trusty 64 位上运行 Python 3.4.0-0ubuntu2。
当试图为我的其他相关(但不重复)找到一个最小示例时 question ,我发现以下使用 Python CTypes 的明显微不足道的代码会在调用 fn1
时导致 SIGABRT
。 (请注意,在另一种情况下,fn1
工作正常,只有 fn2
不起作用,信号是 SIGSEGV
。)
lib.c:
#include <stdio.h>
typedef struct {
int data[3];
} Triplet;
void fn1(Triplet t)
{
fprintf(stderr, "%d, %d, %d\n", t.data[0], t.data[1], t.data[2]);
}
Triplet fn2(Triplet t)
{
Triplet temp = {{t.data[0] + 1, t.data[1] + 1, t.data[2] + 1}};
return temp;
}
主要.py:
from ctypes import *
Array3 = c_int * 3
class Triplet(Union):
_fields_ = [("data", Array3)]
_lib = CDLL("libuniontest.so")
_lib.fn1.argtypes = [Triplet]
_lib.fn2.restype = Triplet
_lib.fn2.argtypes = [Triplet]
t = Triplet(Array3(99, 129, 39))
_lib.fn1(t) # this causes segfault
tt = _lib.fn2(t)
print(tuple(tt.data))
生成文件:
test:
$(CC) -fPIC -shared -o libuniontest.so lib.c
sudo cp libuniontest.so /usr/local/lib/
sudo ldconfig
python3 main.py
如果我将 Union
更改为 Structure
并没有什么不同。
中止的原因是什么,我该如何解决?谢谢。
最佳答案
这似乎是 libffi(这是 ctypes 使用的)中的一个错误,只有当您按值传递一个结构并且该结构的长度在 9-16 字节之间时才会发生:https://bugs.python.org/issue22273
我能够在 python 2.7 上重现它。尝试增加结构的大小或为方法使用指针参数。
不幸的是,直到现在这似乎还没有解决
关于python - 传递包含 3 个整数的数组的 Python CTypes 结构时中止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33563569/