c++ - CPP 中嵌入的 Python : how to get data back to CPP

标签 c++ python boost-python

在从事 C++ 项目时,我一直在寻找第三方库来处理非我的核心业务。我找到了一个非常好的库,完全符合需要,但它是用 Python 编写的。我决定尝试使用 Boost.Python 库在 C++ 中嵌入 Python 代码。

C++ 代码如下所示:

#include <string>
#include <iostream>
#include <boost/python.hpp>

using namespace boost::python;

int main(int, char **) 
{
    Py_Initialize();

    try 
    {
        object module((handle<>(borrowed(PyImport_AddModule("__main__")))));

        object name_space = module.attr("__dict__");
        object ignored = exec("from myModule import MyFunc\n"
                          "MyFunc(\"some_arg\")\n",
                          name_space);

        std::string res = extract<std::string>(name_space["result"]);
    } 
    catch (error_already_set) 
    {
        PyErr_Print();
    }

    Py_Finalize();
    return 0;
}

Python 代码的(非常)简化版本如下所示:

import thirdparty

def MyFunc(some_arg):
    result = thirdparty.go()
    print result

现在问题是这样的: 'MyFunc' 执行良好,我可以看到'result' 的打印。 我不能做的是从 C++ 代码中读取“结果”。 extract 命令永远不会在任何命名空间中找到“结果”。 我尝试将“结果”定义为全局,我什至尝试返回一个元组,但我无法让它工作。

最佳答案

首先,将您的函数更改为 return 值。 print 会使事情复杂化,因为你想取回值(value)。假设你的 MyModule.py 看起来像这样:

import thirdparty

def MyFunc(some_arg):
    result = thirdparty.go()
    return result

现在,要做你想做的事,你必须超越基本的嵌入,如 documentation says .以下是运行函数的完整代码:

#include <Python.h>

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

    Py_Initialize();
    pName = PyString_FromString("MyModule.py");
    /* Error checking of pName left out as exercise */

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

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, "MyFunc");
        /* pFunc is a new reference */

        if (pFunc) {
            pArgs = PyTuple_New(0);
            pArg = PyString_FromString("some parameter")
            /* pArg reference stolen here: */
            PyTuple_SetItem(pArgs, 0, pArg);
            pResult = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pResult != NULL) {
                printf("Result of call: %s\n", PyString_AsString(pResult));
                Py_DECREF(pResult);
            }
            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");
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load module");
        return 1;
    }
    Py_Finalize();
    return 0;
}

关于c++ - CPP 中嵌入的 Python : how to get data back to CPP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/215752/

相关文章:

python - 无法通过pip安装bob包

python - Boost python 构建的共享库不包含任何函数

c++ - VC++ 优化打破了与 NaN 的比较?

php - linux下C和PHP进程间通信有什么好的方法

c++ - 无限循环收集

python - django 应用程序的网络爬虫;我应该用 django 编写还是作为单独的脚本编写

php - 用于在线 Web 编程的 php 替代品?

c++ - 在堆中创建和使用数组

python - 如何从 Python 脚本调用 clang-format

c++ - 在 boost.python 中包装 std::vector<pointer*>