【问题标题】:Abort when passing Python CTypes struct containing array of 3 ints传递包含 3 个整数数组的 Python CTypes 结构时中止
【发布时间】:2015-11-06 09:34:11
【问题描述】:

我在 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;
}

main.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 并没有什么不同。

此中止的原因是什么,我该如何解决?谢谢。

【问题讨论】:

    标签: python c ctypes abort


    【解决方案1】:

    这似乎是 libffi 中的一个错误(这是 ctypes 使用的),如果您按值传递一个结构并且该结构的长度在 9-16 个字节之间,则会发生这种错误:https://bugs.python.org/issue22273

    我可以在 python 2.7 上重现这个。尝试增加结构的大小或为方法使用指针参数。

    不幸的是,这似乎直到现在才解决

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多