当我从 ctypes 调用的 ac 函数实例化 python 对象时,我的嵌入式 Python 3.3 程序会出现段错误。
设置解释器后,我可以成功地从 c main 实例化一个 python Int(以及自定义 c 扩展类型):
#import <Python/Python.h>
#define LOGPY(x) \
{ fprintf(stderr, "%s: ", #x); PyObject_Print((PyObject*)(x), stderr, 0); fputc('\n', stderr); }
// c function to be called from python script via ctypes.
void instantiate() {
PyObject* instance = PyObject_CallObject((PyObject*)&PyLong_Type, NULL);
LOGPY(instance);
}
int main(int argc, char* argv[]) {
Py_Initialize();
instantiate(); // works fine
// run a script that calls instantiate() via ctypes.
FILE* scriptFile = fopen("emb.py", "r");
if (!scriptFile) {
fprintf(stderr, "ERROR: cannot open script file\n");
return 1;
}
PyRun_SimpleFileEx(scriptFile, scriptPath, 1); // close on completion
return 0;
}
然后我使用 PyRun_SimpleFileEx 运行 python 脚本。它似乎运行得很好,但是当它通过 ctypes 调用 instantiate() 时,PyObject_CallObject 中的程序段错误:
import ctypes as ct
dy = ct.CDLL('./emb')
dy.instantiate() # segfaults
lldb 输出:
instance: 0
Process 52068 stopped
* thread #1: tid = 0x1c03, 0x000000010000d3f5 Python`PyObject_Call + 69, stop reason = EXC_BAD_ACCESS (code=1, address=0x18)
frame #0: 0x000000010000d3f5 Python`PyObject_Call + 69
Python`PyObject_Call + 69:
-> 0x10000d3f5: movl 24(%rax), %edx
0x10000d3f8: incl %edx
0x10000d3fa: movl %edx, 24(%rax)
0x10000d3fd: leaq 2069148(%rip), %rax ; _Py_CheckRecursionLimit
(lldb) bt
* thread #1: tid = 0x1c03, 0x000000010000d3f5 Python`PyObject_Call + 69, stop reason = EXC_BAD_ACCESS (code=1, address=0x18)
frame #0: 0x000000010000d3f5 Python`PyObject_Call + 69
frame #1: 0x00000001000d5197 Python`PyEval_CallObjectWithKeywords + 87
frame #2: 0x0000000201100d8e emb`instantiate + 30 at emb.c:9
为什么对实例化()的调用仅从 ctypes 失败?该函数仅在调用 python 库时才会崩溃,所以也许某些解释器状态被 ctypes FFI 调用破坏了?