传递包含3个整数的数组的Python CTypes结构时中止 [英] Abort when passing Python CTypes struct containing array of 3 ints

查看:116
本文介绍了传递包含3个整数的数组的Python CTypes结构时中止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Kubuntu Trusty 64位上运行Python 3.4.0-0ubuntu2。

I'm running Python 3.4.0-0ubuntu2 on Kubuntu Trusty 64 bit.

当试图为我的其他相关问题找到一个最小的例子时(但不能重复) 问题,我发现以下使用Python CType的琐碎代码导致 SIGABRT 调用 fn1 。 (请注意,在另一种情况下, fn1 可以正常工作,只有 fn2 无效并且发出信号是 SIGSEGV 。)

When trying to find a minimal example for my other related (but not duplicate) question, I found that the following apparently trivial code using Python CTypes causes a SIGABRT upon the call to fn1. (Note that in the other case, fn1 worked fine and it was only fn2 which didn't work and the signal was SIGSEGV there.)

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))

Makefile:

test:
    $(CC) -fPIC -shared -o libuniontest.so lib.c
    sudo cp libuniontest.so /usr/local/lib/
    sudo ldconfig
    python3 main.py

如果我将 Union 更改为 Structure 并没有什么不同。

It didn't make a difference if I changed Union to Structure.

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

What is the reason for this abort and how can I fix it? Thanks.

推荐答案

这似乎是libffi(ctypes使用的)错误,只有通过按值的结构,并且该结构的长度介于9-16字节之间: https://bugs.python.org/issue22273

This seems to be a bug in libffi (which is what ctypes uses) that only occurs, if you pass a struct by value and that struct is between 9-16 bytes long: https://bugs.python.org/issue22273

我能够在python 2.7上重现此内容。尝试增加结构的大小或为方法使用指针参数。

I'm able to reproduce this on python 2.7. Try increasing the size of the struct or use a pointer parameter for the methods.

不幸的是,到目前为止,这似乎还没有解决

Unfortunately it seems that this is not fixed until now

这篇关于传递包含3个整数的数组的Python CTypes结构时中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆