繁体   English   中英

在 C++ 中调用 Python

[英]Calling Python in C++

我正在学习 C++,特别是 C 与 Python 的接口。 现在,我的重点是从 C++ 主程序调用或导入 python 对象。

我一直在研究以下链接,但无法理解一些概念。 https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-aC-Cplusplus-code )以下是我无法完全理解的教程部分。

我的问题是:

  1. 调用模块:我假设“CPyObject pModule = PyImport_Import(pName)”正在做这项工作是否正确?
  2. 对象的导入:

一世。 我假设“CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger")" 正在做这项工作是否正确?

ii.If I want to import a dataframe from python to C++ as a CPyObject, how can I manipulate this object in C++. 我问是因为在 C++ 中没有与 dataframe 等效的 object。 3) 我还需要做些什么来确保我的 Python 模块文件对 C++ 可见且可调用吗? 比如将它们保存在同一个文件夹中?

Consider the following Python program, stored in pyemb3.py:

def getInteger():

print('Python function getInteger() called')

c = 100*50/30

return c

Now we want to call the function getInteger() from the following C++ code and print the value returned this function. This is the client C++ code:

#include <stdio.h>
#include <Python.h>
#include <pyhelper.hpp>
    
int main()
     {
    CPyInstance hInstance;

    CPyObject pName = PyUnicode_FromString("pyemb3");
    CPyObject pModule = PyImport_Import(pName);

    if(pModule)
    {
        CPyObject pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if(pFunc && PyCallable_Check(pFunc))
        {
            CPyObject pValue = PyObject_CallObject(pFunc, NULL);

            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }

    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    return 0;
}

问题是100*50/30不是integer ,它是float

要获得 integer 使用 integer 除法: 100*50//30

如果您不确定返回的类型,您可以在pValue上使用Py_TYPE宏,或者只是简单地检查您要查找的类型: PyLong_CheckPyLong_CheckExact

1:如果PyImport_Import不返回 null 则导入成功,并且在 function 返回时模块已经执行。

2: PyObject_GetAttrStringPyObject_GetAttr是获取导入模块对象的正确方法。

3:使用这些标志来确保 Python 被嵌入。 Py_SetPath之前使用Py_Initialize将模块的路径添加到sys.path

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM