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

2024-10-01 09:40:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从C调用一个在python模块中定义的自定义函数,我有一些初步的代码来完成这项工作,但它只是将输出输出输出到标准输出。

mytest.py

import math

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

测试.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中使用?


Tags: 模块函数代码pyimport标准return定义
3条回答

如前所述,使用PyRun_SimpleString似乎是个坏主意。

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

阅读导言是理解其工作方式的第一步。

首先,您必须了解PyObject,它是C API的基本对象。它可以表示任何类型的python基本类型(string、float、int…)。

有许多函数可以将python string转换为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 result = PyFloat_AsDouble(myResult);

显然,您应该检查错误(参见Mark Tolonen给出的链接)。

如果你有任何问题,不要犹豫。祝你好运。

调用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;
}

下面是我编写的一个示例代码(在各种在线资源的帮助下)将字符串发送到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运行此进程。我在读红帽。我建议使用PyErr_Print();进行错误检查。

相关问题 更多 >