如何从 C 的 PyObject 类型的函数 return 到 python 的值?

How to return a value from C to python from C's PyObject type of functions?

我试图通过从 python 调用 C 文件来传递一个值,然后 return 该值再次从 C 调用到 python。

我的问题是如何做到这一点?可以用returnPy_BuildValue(a+b)之类的东西吗?

#include <Python.h>

static PyObject *
hello_world(PyObject *self, PyObject *noargs)
{
   int a=5,b=10;

   return Py_BuildValue(a+b); //This is Errorus.
}


static PyMethodDef
module_functions[] = {
    { "hello_world", hello_world, METH_NOARGS, "hello world method" },
    { NULL }
};



PyMODINIT_FUNC
inittesty2(void)
{
    Py_InitModule("testy2", module_functions);
}

指定值的格式:

return Py_BuildValue("i", a+b); // "i" for int

您可以找到更多格式单元 here (Py_BuildValue documentation)

您可以使用整数的显式构造函数 PyInt_FromLong or PyLong_FromLong

您可以为使用 Py_BuildValue 创建的任何类型找到这样的函数,并在顶部获得一点类型安全。