SystemError: error return without exception set

SystemError: error return without exception set

我正在学习嵌入 Python,在我的测试程序中,我从我的 C 应用程序调用 Python 代码,然后 Python 代码调用我的方法已提供:

#include <Python.h>

// The callback function.
extern "C" PyObject * printHello(PyObject *self, PyObject *args) {
    printf("hello from C\n");
    return 0;
}

PyMethodDef methods [] = {
    { "printHello", printHello, METH_NOARGS, "docs docs docs" },
    { 0, 0, 0, 0 },
};

int main(int argc, char *argv[])
{
    Py_Initialize();
    Py_InitModule("emb", methods);
    PyRun_SimpleString(
                "import emb\n"
                "emb.printHello()\n"
                );
    Py_Finalize();
    return 0;
}

程序运行并调用了我的函数,但是在 returning 时我得到一个异常:

hello from C
Traceback (most recent call last):
  File "", line 2, in 
SystemError: error return without exception set

我认为这与调用约定或我的回调函数的签名有关。

特别是,是因为我 returning 0 吗?我的函数实际上不需要 return 任何东西,这就是为什么我 return 0。我会使用 void printHello(),但是 PyCFunction 要求签名是 PyObject * func(PyObject *self, PyObject *args);

你是对的,你的函数并不真的需要 return 任何东西(在这种情况下),但是,在 Python 中,"not returning anything" 意味着 return正在 None。尝试替换

return 0;

在你的 printHello 函数中

Py_INCREF(Py_None);
return Py_None;

第一行递增 None 的引用计数,第二行 return 递增。

更好的是,只需使用 Py_RETURN_NONE(也就是 shorthand):

extern "C" PyObject * printHello(PyObject *self, PyObject *args) {
    printf("hello from C\n");
    Py_RETURN_NONE;
}