我目前正在尝试学习如何用 C 编写 Python 扩展,一切似乎都进展顺利。但是,当我尝试使用比较函数时,它们都会导致 Segmentaion 错误。例如:
#include "Python.h"
int test(void) {
int result;
printf("Before compare...\n");
result = PyObject_Compare(PyInt_FromLong(1), PyInt_FromLong(3));
printf("result= %d\n", result);
return 0;
}
从 Python执行test()
(我使用 ctypes)给出以下输出:
Before compare...
Segmentation fault
这发生在我身上,用于其他比较功能,例如:PyObject_cmp
...等
任何帮助表示赞赏,谢谢。
更多信息:
我首先将文件(test.c)编译为共享库:
$> python-config --cflags
-I/usr/include/python2.7 -I/usr/include/python2.7 -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes
$> python-config --ldflags
-L/usr/lib/python2.7/config -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions
$> gcc -c $(python-config --cflags) ./test.c -o test.o
$> gcc -shared ./test.o $(python-config --ldflags) -o libtest.so
然后我像这样从 Python 启动函数:
import ctypes
testlib = ctypes.CDLL('./libtest.so')
testlib.test()
编辑:
使用 Viktor 给出的测试
$> gcc -o dlltest test.c -ldl
$> gdb dlltest
(gdb) run
Starting program: dlltest
[Thread debugging using libthread_db enabled]
Cannot find new threads: generic error
(gdb)
所以我这样做了:
$> LD_PRELOAD=libpthread-2.13.so gdb dlltest
(gdb) run
Starting program: dlltest
[Thread debugging using libthread_db enabled]
Before compare...
result= -1
[Inferior 1 (process 3274) exited normally]
(gdb)
编辑2:
>$ gdb --args python frompython.py
(gdb) run
Starting program: /usr/bin/python frompython.py
[Thread debugging using libthread_db enabled]
Before compare...
Program received signal SIGSEGV, Segmentation fault.
0x080a855b in PyObject_Compare ()
(gdb) backtrace
#0 0x080a855b in PyObject_Compare ()
#1 0x005225d8 in test () at ./testmod.c:29
#2 0x005181ca in ffi_call_SYSV ()
from /usr/lib/python2.7/lib-dynload/_ctypes.so
#3 0x00517eff in ffi_call () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#4 0x00510312 in _ctypes_callproc ()
from /usr/lib/python2.7/lib-dynload/_ctypes.so
#5 0x0050788d in ?? () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#6 0x0805dc31 in PyObject_Call ()
#7 0x080f81c1 in PyEval_EvalFrameEx ()
#8 0x080fd804 in PyEval_EvalCodeEx ()
#9 0x080fe177 in PyEval_EvalCode ()
#10 0x0811acd0 in ?? ()
#11 0x0811b8e9 in PyRun_FileExFlags ()
#12 0x0811c4cc in PyRun_SimpleFileExFlags ()
#13 0x0812c7c6 in Py_Main ()
#14 0x0805da0b in main ()
(gdb)