从C/C++调用Python方法并提取其返回值

90 投票
10 回答
122717 浏览
提问于 2025-04-16 01:32

我想从C语言中调用一个在Python模块里定义的自定义函数。我已经有了一些初步的代码,但它只是把输出打印到了标准输出。

mytest.py

import math

def myabs(x):
    return math.fabs(x)

test.cpp

#include <Python.h>

int main() {
    Py_Initialize();
    PyRun_SimpleString("import sys; sys.path.append('.')");
    PyRun_SimpleString("import mytest;");
    PyRun_SimpleString("print mytest.myabs(2.0)");
    Py_Finalize();

    return 0;
}

我该如何把返回值提取到C语言中的一个double类型,并在C语言中使用它呢?

10 个回答

11

一个完整的示例,展示了如何调用一个Python函数并获取结果,可以在这个链接找到:http://docs.python.org/release/2.6.5/extending/embedding.html#pure-embedding

#include <Python.h>

int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}
33

这里有一段我写的示例代码(参考了各种在线资源),它可以把一个字符串发送到Python代码中,然后返回一个值。

这是C语言的代码,文件名是 call_function.c

#include <Python.h>
#include <stdlib.h>
int main()
{
   // Set PYTHONPATH TO working directory
   setenv("PYTHONPATH",".",1);

   PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;


   // Initialize the Python Interpreter
   Py_Initialize();


   // Build the name object
   pName = PyString_FromString((char*)"arbName");

   // Load the module object
   pModule = PyImport_Import(pName);


   // pDict is a borrowed reference 
   pDict = PyModule_GetDict(pModule);


   // pFunc is also a borrowed reference 
   pFunc = PyDict_GetItemString(pDict, (char*)"someFunction");

   if (PyCallable_Check(pFunc))
   {
       pValue=Py_BuildValue("(z)",(char*)"something");
       PyErr_Print();
       printf("Let's give this a shot!\n");
       presult=PyObject_CallObject(pFunc,pValue);
       PyErr_Print();
   } else 
   {
       PyErr_Print();
   }
   printf("Result is %d\n",PyInt_AsLong(presult));
   Py_DECREF(pValue);

   // Clean up
   Py_DECREF(pModule);
   Py_DECREF(pName);

   // Finish the Python Interpreter
   Py_Finalize();


    return 0;
}

这是Python代码,保存在文件 arbName.py 中:

 def someFunction(text):
    print 'You passed this Python program '+text+' from C! Congratulations!'
    return 12345

我使用命令 gcc call_function.c -I/usr/include/python2.6 -lpython2.6 ; ./a.out 来运行这个过程。我是在redhat系统上。建议使用 PyErr_Print(); 来检查错误。

104

之前提到过,使用 PyRun_SimpleString 似乎不是个好主意。

你应该使用 C-API 提供的方法(http://docs.python.org/c-api/)。

首先,阅读介绍是理解它工作原理的第一步。

首先,你需要了解 PyObject,这是 C API 的基本对象。它可以表示任何类型的 Python 基本数据类型(比如字符串、浮点数、整数等)。

有很多函数可以用来转换,比如将 Python 字符串转换为 char* 或者将 PyFloat 转换为 double。

首先,导入你的模块:

PyObject* myModuleString = PyString_FromString((char*)"mytest");
PyObject* myModule = PyImport_Import(myModuleString);

然后获取你想要调用的函数的引用:

PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs");
PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0));

接着获取你的结果:

PyObject* myResult = PyObject_CallObject(myFunction, args)

最后将结果转换回 double 类型:

double result = PyFloat_AsDouble(myResult);

当然,你应该检查错误(参考 Mark Tolonen 提供的链接)。

如果你有任何问题,随时问我。祝你好运。

撰写回答