在C+中调用Python+; 我正在学习C++,特别是C接口到Python。现在,我的重点是从C++主程序调用或导入Python对象。
我一直在研究下面的链接,但无法理解一些概念。() 以下是我无法完全理解的教程部分 我的问题是:在C+中调用Python+; 我正在学习C++,特别是C接口到Python。现在,我的重点是从C++主程序调用或导入Python对象。,python,c++,object,import,module,Python,C++,Object,Import,Module,我一直在研究下面的链接,但无法理解一些概念。() 以下是我无法完全理解的教程部分 我的问题是: 调用模块: 我假设“CPyObject pModule=PyImport_Import(pName)”正在做这项工作是否正确 导入对象: 一,。假设“CPyObject pFunc=PyObject_GetAttrString(pModule,“getInteger”)”正在执行此任务,对吗 如果我想把Python中的DATAFRAMB导入到C++中作为一个CpyObjor,那么我如何在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;
}
考虑存储在pyemb3.py中的以下Python程序:
def getInteger():
print('调用了Python函数getInteger()')
c=100*50/30
返回c
现在我们想从下面的C++代码调用函数GigIngEnter(),并打印返回这个函数的值。这是客户端C++代码:
#包括
#包括
#包括
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_检查(pFunc))
{
CPyObject pValue=PyObject_CallObject(pFunc,NULL);
printf_s(“C:getInteger()=%ld\n”,PyLong_AsLong(pValue));
}
其他的
{
printf(“错误:函数getInteger()\n”);
}
}
其他的
{
printf_s(“错误:模块未导入\n”);
}
返回0;
}
问题在于100*50/30
不是一个整数,而是一个浮点
要获取整数,请使用整数除法:100*50//30
如果不确定返回的类型,可以使用pValue
上的Py_type
宏,或者只需使用:或
1:如果PyImport\u Import
未返回null,则导入成功,并且在函数返回时模块已执行
2:or是获取导入模块对象的正确方法
3:使用这些来确保嵌入Python。使用beforePy\u Initialize
将模块路径添加到sys.path