【问题标题】:How to return a value from C to python from C's PyObject type of functions?如何从 C 的 PyObject 类型的函数将值从 C 返回到 python?
【发布时间】:2016-03-23 15:34:15
【问题描述】:

我试图通过从 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);
}

【问题讨论】:

    标签: python c python-c-api python-c-extension python-extensions


    【解决方案1】:

    指定值的格式:

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

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

    【讨论】:

      【解决方案2】:

      您可以改用整数 PyInt_FromLongPyLong_FromLong 的显式构造函数。

      您可以为使用 Py_BuildValue 创建的任何类型找到类似的函数,并在上面获得一点类型安全性。

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 1970-01-01
        相关资源
        最近更新 更多