问题描述
我在使用 Python C api 创建 PyTupleObject 时遇到困难。
#include "Python.h"
int main() {
int err;
Py_ssize_t size = 2;
PyObject *the_tuple = PyTuple_New(size); // this line crashes the program
if (!the_tuple)
std::cerr << "the tuple is null" << std::endl;
err = PyTuple_SetItem(the_tuple,(Py_ssize_t) 0,PyLong_FromLong((long) 5.7));
if (err < 0) {
std::cerr << "first set item Failed" << std::endl;
}
err = PyTuple_SetItem(the_tuple,(Py_ssize_t) 1,PyLong_FromLong((long) 5.7));
if (err < 0) {
std::cerr << "second set item Failed" << std::endl;
}
return 0;
}
崩溃
Process finished with exit code -1073741819 (0xC0000005)
但到目前为止我尝试过的其他一切也是如此。任何想法我做错了什么?并不是说我只是想将其作为 C++ 程序运行,因为我只是想在添加 swig 类型映射之前对代码进行测试。
解决方法
评论者@asynts 是正确的,如果您想与 Python 对象交互(实际上您是嵌入 Python),您需要通过 Py_Initialize 初始化解释器。 API 中有一个 subset of functions 可以在不初始化解释器的情况下安全地调用,但创建 Python 对象不属于这个子集。
Py_BuildValue 可能会“工作”(例如,不会使用这些特定参数创建段错误),但如果您在未初始化解释器的情况下尝试对其进行任何操作,则会导致代码中的其他地方出现问题。
您似乎是在尝试扩展 Python 而不是嵌入它,但您嵌入它是为了测试扩展代码。您可能需要参考 official documentation for extending Python with C/C++ 来指导您完成此过程。