我从这里复制的示例:https://docs.python.org/3.5/extending/embedding.html
#include <Python.h>
int
main(int argc, char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
Py_Finalize();
PyMem_RawFree(program);
return 0;
}
如果像这样编译和链接:
gcc -fno-diagnostics-color -Wall -Wno-unused-function -fPIC -ggdb \
-I. -I/usr/include/python3.5m -c test_embed.c -o test_embed.o
gcc -fno-diagnostics-color -Wall -Wno-unused-function -fPIC -ggdb \
-I. -I/usr/include/python3.5m -shared -lpython3.5m ./test_embed.o \
-o test_embed
运行时出现段错误并破坏堆栈,以至于无法弄清楚发生了什么。我需要任何特定的设置来编译它吗?
当我使用 /usr/bin/python3.5-config --cflags
给出的编译器选项时和 /usr/bin/python3.5-config --ldconfig
,该示例不会构建,因为它无法在共享对象中找到符号。
根据要求,这里是编译和链接命令以及错误输出:
$ gcc $(python3.5-config --cflags) -c test_embed.c -o test_embed.o
$ gcc $(python3.5-config --ldflags) ./test_embed.o -o test_embed
./test_embed.o: In function `main':
redacted/test_embed.c:6: undefined reference to `Py_DecodeLocale'
redacted/test_embed.c:11: undefined reference to `Py_SetProgramName'
redacted/test_embed.c:12: undefined reference to `Py_Initialize'
redacted/test_embed.c:13: undefined reference to `PyRun_SimpleStringFlags'
redacted/test_embed.c:15: undefined reference to `Py_Finalize'
redacted/test_embed.c:16: undefined reference to `PyMem_RawFree'
collect2: error: ld returned 1 exit status
$ python3.5-config --ldflags
-L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -L/usr/lib -lpython3.5m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions
最佳答案
您的 test_embed
二进制段错误,因为使用 --shared
(共享库)构建的二进制文件不打算运行。
诊断导致您在链接器命令行中错误地使用 --shared
的构建问题可能需要更多详细信息,例如您使用的特定 gcc
命令以及运行它们的错误消息,或者系统上 python3.5-config
的输出,也许两者都有。如果我使用以下命令编译您的测试程序,它不会出现段错误(它会打印预期的输出)。
gcc $(python3.5-config --cflags) -c test_embed.c -o test_embed.o
gcc $(python3.5-config --ldflags) ./test_embed.o -o test_embed
在我的系统上,python3.5-config --ldflags
的输出不包括 --shared
。
构建文档Building C and C++ Extensions在其 distutils 中包含示例编译命令部分。那里的示例链接命令包括 --shared
用于它生成的 .so
文件,但该 .so
文件旨在导入到python 解释器,不作为命令调用。
关于python - Python 解释器嵌入段错误的最小示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49551375/