python - 传递包含 3 个整数的数组的 Python CTypes 结构时中止

标签 python c ctypes abort

我在 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/

相关文章:

c - 以二进制格式写入文件时输出错误

python - 无法使用 ctypes.pythonapi 调整元组的大小

python - 与 ctypes 的联合运算不起作用

python - 让 C 库使用 ctypes 调用 python 函数

python - 带小数点的 openpyxl 格式化单元格

c - 如何将 void* 指针包装到 TCL 对象中

c Valgrind 大小 4 的读取无效 -> 段错误

python - 如何在 Python 中查找奇数索引处的元素之和

python - 使用唯一键和所有相关值将列表列表转换为字典

python - tkinter 程序的窗口大小