1
我在Kubuntu Trusty 64位上運行Python 3.4.0-0ubuntu2。當傳遞Python CTypes結構包含3個整數的數組結構
當試圖找到我的其他相關小例子(但不重複)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))
的Makefile:
test:
$(CC) -fPIC -shared -o libuniontest.so lib.c
sudo cp libuniontest.so /usr/local/lib/
sudo ldconfig
python3 main.py
它沒有做區別如果我將Union
更改爲Structure
。
這個中止的原因是什麼?我該如何解決?謝謝。