我正在学习C ++,尤其是Python的C接口。现在,我的重点是从C ++主程序调用或导入python对象。
我一直在研究以下链接,但无法理解某些概念。 (https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code) 以下是本教程中我无法完全理解的部分。
我的问题是:
i。假设“ cpyObject pFunc = PyObject_GetAttrString(pModule,“ getInteger”)“在做这项工作对我来说是否正确?
ii。如果我想将数据帧从python作为cpyObject导入C ++,如何在C ++中操作该对象。我问是因为在C ++中没有等效于dataframe的对象。 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;
}