【问题标题】:Calling a python method from C/C++, and extracting its return value从 C/C++ 调用 python 方法,并提取其返回值
【发布时间】:2011-03-18 05:14:53
【问题描述】:

我想从 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 中使用?

【问题讨论】:

  • 你读过这个:docs.python.org/c-api?它似乎回答了你的问题。 docs.python.org/c-api/number.html#PyNumber_Float 似乎就是您要找的东西。它出什么问题了?你还需要什么?
  • 真正的问题是如何从mytest.myabs(2.0) 访问返回的对象。一旦有了指向它的指针,我就可以使用 PyNumber_Float 函数轻松地将其转换为浮点数。
  • 我们可以通过代码示例看到答案并完成它吗?

标签: c++ python c python-c-api python-embedding


【解决方案1】:

您必须以某种方式提取 python 方法并使用PyObject_CallObject() 运行它。为此,您可以为 Python 提供一种设置函数的方法,就像 Extending and Embedding Python Tutorial 示例所做的那样。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    【解决方案3】:

    如果将返回值分配给变量,则可以使用 PyEval_GetGlobals() 和 PyDict_GetItemString() 之类的方法来获取 PyObject。从那里,PyNumber_Float 可以得到你想要的值。

    我建议浏览整个 API - 当您看到可用的不同方法时,某些事情会变得很明显,并且可能有比我描述的方法更好的方法。

    【讨论】:

      【解决方案4】:

      如前所述,使用 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 result = PyFloat_AsDouble(myResult);
      

      您显然应该检查错误(参见 Mark Tolonen 提供的链接)。

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

      【讨论】:

      • 由于有用的提示,我会接受你的回答,但如果你能提供一个完整的工作 C 模块来调用上述 python 函数,那对我会更有帮助。
      • 如果你正在调用一个对象的类方法,你需要在args中传递那个对象吗?
      • 虽然它被接受,但不幸的是,这个答案不是调用 Python 代码的好模板(我在其他地方看到过它的引用)。 PyTuple_Pack 行在每次执行时都会泄漏一个 float 对象。无需手动转换和创建元组即可调用该函数,result = PyObject_CallFunction(myFunction, "d", 2.0)。导入可以写成module = PyImport_ImportModule("mytest")(不创建 Python 字符串)。
      • 这对调用类中定义的函数有效吗?
      • 如果你使用 Python >3.5,PyString_FromString()PyUnicode_FromString()
      【解决方案5】:

      我已经使用 BOOST 将 Python 嵌入到 C++ [这个工作的 C 模块应该有所帮助]

      #include <boost/python.hpp>
      
      void main()
      {
      using namespace boost::python;
       Py_Initialize();
       PyObject* filename = PyString_FromString((char*)"memory_leak_test");
           PyObject* imp = PyImport_Import(filename);
           PyObject* func = PyObject_GetAttrString(imp,(char*)"begin");
           PyObject* args = PyTuple_Pack(1,PyString_FromString("CacheSetup"));
           PyObject* retured_value = PyObject_CallObject(func, args); // if you have arg
           double retured_value = PyFloat_AsDouble(myResult);
       std::cout << result << std::endl;
       Py_Finalize();
      }
      

      【讨论】:

      • 这个脚本中的 boost 部分在哪里?
      【解决方案6】:

      这是我编写的示例代码(借助各种在线资源)将字符串发送到 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();用于错误检查。

      【讨论】:

      • 调用a.out 会比./a.out 更好,因为你对a.out 的调用依赖于PATH 中的工作目录,这不是一个非常常见的配置。您还应该考虑向 GCC 提供 -o 选项,以便为可执行文件提供更好的名称。
      • 参见 Meta SE 上的 How does editing work?。如果您可以访问修订历史记录但看不到标记的更改,只需将差异视图切换到side-by-side markdown。修订历史中每个修订的顶部都有用于切换差异视图的按钮。如果您不了解标记的作用,请参阅editing help。如果您正在编辑帖子,编辑器具有内置帮助 - 请参阅编辑器右上角的橙色问号。
      • 这给了我关于 python 2.7 的段错误:(
      • 编译行(c++):g++ call_function.cpp python2.7-config --cflags python2.7-config --ldflags -o call_function
      • 在python3中将PyString_FromString替换为PyUnicode_FromStringPy_Finalize替换为Py_FinalizeEx
      【解决方案7】:

      为防止出现其他答案中的额外 .py 文件,您只需检索 __main__ 模块,该模块由第一次调用 PyRun_SimpleString 创建:

      PyObject *moduleMainString = PyString_FromString("__main__");
      PyObject *moduleMain = PyImport_Import(moduleMainString);
      
      PyRun_SimpleString(
          "def mul(a, b):                                 \n"\
          "   return a * b                                \n"\
      );
      
      PyObject *func = PyObject_GetAttrString(moduleMain, "mul");
      PyObject *args = PyTuple_Pack(2, PyFloat_FromDouble(3.0), PyFloat_FromDouble(4.0));
      
      PyObject *result = PyObject_CallObject(func, args);
      
      printf("mul(3,4): %.2f\n", PyFloat_AsDouble(result)); // 12
      

      【讨论】:

        【解决方案8】:

        以下是对您问题的简单直接的回答:

            #include <iostream>
            #include <Python.h>
            using namespace std;
            int main()
            {
            const char *scriptDirectoryName = "/yourDir";
            Py_Initialize();
            PyObject *sysPath = PySys_GetObject("path");
            PyObject *path = PyString_FromString(scriptDirectoryName);
            int result = PyList_Insert(sysPath, 0, path);
            PyObject *pModule = PyImport_ImportModule("mytest");
        
            PyObject* myFunction = PyObject_GetAttrString(pModule,(char*)"myabs");
            PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(-2.0));
        
        
            PyObject* myResult = PyObject_CallObject(myFunction, args);
            double getResult = PyFloat_AsDouble(myResult);
            return 0;
            }
        

        【讨论】:

        • 我收到以下错误:“PyString_FromString”未在此范围内声明 PyObject *path = PyString_FromString(scriptDirectoryName);
        【解决方案9】:

        这是一个也适用于 Python 3 的最小可执行版本(使用 Python 2.7 和 3.9 测试)。

        文档的链接包含在 cmets 中,但都可以在 https://docs.python.org/3/c-api/ 下访问

        #include <Python.h>
        #include <stdio.h>
        
        int main()
        {
            // Initialize the Python Interpreter
            Py_Initialize();
        
            // see https://docs.python.org/3/c-api/structures.html
            // NULL objects are special and Py_CLEAR knows this
            PyObject *module = NULL, *result = NULL;
        
            // https://docs.python.org/3/c-api/import.html
            module = PyImport_ImportModule("mytest");
            if (!module) {
                // Python generally uses exceptions to indicate an error state which
                // gets flagged in the C-API (a NULL pointer in this case) indicating
                // "something" failed. the PyErr_* API should be used to get more
                // details
                goto done;
            }
        
            // see https://docs.python.org/3/c-api/call.html#c.PyObject_CallMethod
            // and https://docs.python.org/3/c-api/arg.html#building-values
            result = PyObject_CallMethod(module, "myabs", "f", 3.14);
            if (!result) {
                goto done;
            }
        
            // make sure we got our number back
            if (PyFloat_Check(result)) {
                printf("Successfully got a float: %f\n", PyFloat_AsDouble(result));
            } else {
                printf("Successfully got something unexpected!\n");
            }
        
          done:
            // see https://docs.python.org/3/c-api/exceptions.html
            PyErr_Print();
        
            // see https://docs.python.org/3/c-api/refcounting.html
            Py_CLEAR(result);
            Py_CLEAR(module);
        
            // Optionally release Python Interpreter
            Py_Finalize();
        
            return 0;
        }
        

        这使用了 OP 的 Python 代码 mytest.py,或者这个等效的一行代码:

        from math import fabs as myabs
        

        构建将是特定于 OS/Python 版本的,但以下对我有用:

        cc -o test -I/usr/include/python3.9 /usr/lib/libpython3.9.so test.c
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-12
          • 1970-01-01
          • 1970-01-01
          • 2016-08-15
          相关资源
          最近更新 更多