简体   繁体   English

使用 Python 的 C API 创建一个基本的 PyTupleObject

[英]Creating a basic PyTupleObject using Python's C API

I'm having difficulty with creating a PyTupleObject using the Python C api.我在使用 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;

}

crashes with崩溃

Process finished with exit code -1073741819 (0xC0000005)

But so does everything else i've tried so far.但到目前为止我尝试过的所有其他事情也是如此。 Any ideas what I'm doing wrong?任何想法我做错了什么? Not that I'm just trying to run the as a C++ program, as I'm just trying to do tests on the code before adding a swig typemap.并不是说我只是想将其作为 C++ 程序运行,因为我只是想在添加 swig 类型映射之前对代码进行测试。

The commenter @asynts is correct in that you need to initialize the interpreter via Py_Initialize if you want to interact with Python objects (you are, in fact, embedding Python).评论者@asynts 是正确的,因为如果您想与 Python 对象交互(实际上是嵌入 Python),您需要通过Py_Initialize初始化解释器。 There are a subset of functions from the API that can safely be called without initializing the interpreter, but creating Python objects do not fall within this subset. API的函数子集可以在不初始化解释器的情况下安全地调用,但创建 Python 对象不属于该子集。

Py_BuildValue may "work" (as in, not creating a segfault with those specific arguments), but it will cause issues elsewhere in the code if you try to do anything with it without having initialized the interpreter. Py_BuildValue 可能“工作”(例如,不使用这些特定参数创建段错误),但如果您尝试在未初始化解释器的情况下对其进行任何操作,它将导致代码中的其他地方出现问题。

It seems that you're trying to extend Python rather than embed it, but you're embedding it to test the extension code.您似乎正在尝试扩展 Python 而不是嵌入它,但您正在嵌入它来测试扩展代码。 You may want to refer to the official documentation for extending Python with C/C++ to guide you through this process.您可能需要参考官方文档以使用 C/C++ 扩展 Python以指导您完成此过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM