gpt4 book ai didi

python - 如何从 C 的 PyObject 类型的函数将值从 C 返回到 python?

转载 作者:太空狗 更新时间:2023-10-29 16:11:08 25 4
gpt4 key购买 nike

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

我的问题是如何做到这一点?可以使用 return Py_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) .

关于python - 如何从 C 的 PyObject 类型的函数将值从 C 返回到 python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34329970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com