python - Py_BuildValue 和 PyArg_ParseTuple Seg 错误

标签 python c++

编辑:我在流程开始时错过了 Py_Initialize()

我在使用 Py_BuildValue 和 PYArg_ParseTuple 时遇到一些奇怪的行为。

首先,每当我尝试构建一个整数时,我都会在 Py_BuildValue 处遇到段错误。 对于 float 、对象或字符串,不会发生这种情况。

其次,当我尝试解析元组时,除非我解析包含单个字符串:“s”或单个 PyObject:“O”的元组,否则我也会遇到 seg 错误。 (如果我尝试同时解析两者,我也会遇到段错误:“Os”)

以下是两个出现段错误的示例:

#include <Python.h>
#include <iostream>

using namespace std;

int main() {
    Py_Initialize(); // <-- Missing this
    PyObject* pString = Py_BuildValue("s", "hello"); //<- Works fine
    PyObject* pFloat = Py_BuildValue("f", 2.3); //<- Works fine

    PyObject* pInt = Py_BuildValue("i", 2); // <- Seg faults

    return 0;
}

以及 ParseTuple 的示例(针对正确的构建值进行编辑并测试 api 调用):

#include <Python.h>
#include <iostream>

using namespace std;

int main() {
    Py_Initialize(); // <-- Missing this
    PyObject* pFloat = Py_BuildValue("f", 2.3);
    if(!pFloat)
        cout << "Error Float" << endl;

    PyObject *pTuple = PyTuple_New(1);
    if(!pTuple)
        cout << "Error Creating Tuple" << endl;

    if(PyTuple_SetItem(pTuple, 0, pFloat)) //Returns 0 on success
        cout << "Error Set Item" << endl;

    // parse tuple items
    float f;
    if(!PyArg_ParseTuple(pTuple, "f", &f))
        PyErr_SetString(PyExc_TypeError, "invalid parameter");

    return 0;
}

我在 RedHat 上运行 anaconda python 2.7

我编译:

g++ `python-config --cflags` -L/home/user/anaconda/lib/ -lpython2.7 test.cpp -o test.out

使用 anaconda python 可能有问题吗?我已将问题分解为我能想到的最简单的情况......

最佳答案

我发现几个问题。

Py_BuildValuef 选项从 C/C++ double 构造 Python float 。您传递了一个字符串,而不是一个 double 。

每次调用 Python C-API 函数后,您都需要测试返回值以查看是否发生错误。每次调用后都需要执行此操作。

编辑 - 还有一个问题。

将 Python C-API 调用嵌入到 C/C++ 程序中时,需要通过调用 Py_Initialize() 来初始化解释器。

关于python - Py_BuildValue 和 PyArg_ParseTuple Seg 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33631353/

相关文章:

c++ - C++ 中宏的二元运算

c++ - 运算符 << 作为成员函数

python - 在 Python 中比较 float 和 int

python - 值错误: Cannot take the length of Shape with unknown rank

c++ - MacOSX 上的 Qt Creator 或 qmake 构建库为 ".so"而不是 dylib

c++ - 如何获取指针类型的指向类型?

c++ - 与 friend 一起上课而不是前向声明,: which compiler is correct

python - 如何删除 for 循环中的标签

python - 读取 CSV 数据并将其添加到字典中

python - ID 生成器 : class variable vs while yield