一、代码块
#include <iostream> //使用标准流
#include "Python.h"
#include <string>
using namespace std; //导入std名字空间
int PreDepth(int*);
int main()
{
cout << "Starting Prediction..." << endl;
cout << "PreDepth()-------------" << endl;
int a[1026] = { 2,3,3 };
cout << PreDepth(a) << endl;
cout << "END----------------------" << endl;
system("pause");
return 0;
}
//调用输出"Hello World"函数
int PreDepth(int*input)
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
PyObject * pModule = NULL;//声明变量
PyObject *pReturn = NULL;
PyObject * pFunc = NULL;//声明变量
pModule = PyImport_ImportModule("MyCt"); //这里是要调用的Python文件名
pFunc = PyObject_GetAttrString(pModule, "PreDepth");//这里是要调用的函数名
PyObject *pArgs = PyTuple_New(1); //函数调用的参数传递均是以元组的形式打包的,2表示参数个数
PyObject*pList = PyList_New(0);
for (int i = 0; i < 1026; i++) {
PyList_Append(pList, Py_BuildValue("i", input[i]));
}
PyTuple_SetItem(pArgs, 0, pList);
pReturn = PyEval_CallObject(pFunc, pArgs); //调用函数,NULL表示参数为空
int result;
PyArg_Parse(pReturn, "i", &result);//i表示转换成int型变量
cout << "result= " << result << endl;
Py_Finalize();//调用Py_Finalize,这个和Py_Initialize相对应的.
return result;
}
二、 c++运行python代码
#include<python.h>
#include<iostream>
int main()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
PyRun_SimpleString("print('hello world!')");
PyRun_SimpleString("def fun:
print('test');
")
Py_Finalize();
return 0;
}
三、c++调用python函数并输出返回值
3.1、定义python函数
def add(a,b):
return a+b
3.2、测试
#include <Python.h>
#include<iostream>
using namespace std;
int main()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
if (!Py_IsInitialized())
{
printf("初始化失败!");
return 0;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
PyObject * pModule = NULL;//声明变量
PyObject * pFunc = NULL;// 声明变量
pModule = PyImport_ImportModule("pythonTest");//这里是要调用的文件名hello.py
if (pModule == NULL)
{
cout << "没找到" << endl;
}
pFunc = PyObject_GetAttrString(pModule, "add_num");//这里是要调用的函数名
PyObject* args = Py_BuildValue("(ii)", 28, 103);//给python函数参数赋值
PyObject* pRet = PyObject_CallObject(pFunc, args);//调用函数
int res = 0;
PyArg_Parse(pRet, "i", &res);//转换返回类型
cout << "res:" << res << endl;//输出结果
Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。
return 0;
}
注意:请将python文件放在c++项目的根目录或者改变测试代码中的python文件的路径。
四、调用python的类
int test03()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
if (!Py_IsInitialized())
{
printf("初始化失败!");
return 0;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
PyObject * pModule = NULL;//声明变量
PyObject * pFunc = NULL;// 声明变量
PyObject * pClass = NULL;//声明变量
PyObject * pInstance = NULL;
pModule = PyImport_ImportModule("pythonTest");//这里是要调用的文件名hello.py
if (pModule == NULL)
{
cout << "没找到" << endl;
}
// 模块的字典列表
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary./n");
return -1;
}
//获取calc类
PyObject* pClassCalc = PyDict_GetItemString(pDict, "calc");
if (!pClassCalc) {
printf("Cant find calc class./n");
return -1;
}
//构造Person的实例
PyObject* pInstanceCalc = PyInstanceMethod_New(pClassCalc);
if (!pInstanceCalc) {
printf("Cant find calc instance./n");
return -1;
}
PyObject* pRet = PyObject_CallMethod(pClassCalc,"add","10","10", pInstanceCalc);
if (!pRet)
{
printf("不能找到 pRet");
return -1;
}
int res = 0;
PyArg_Parse(pRet, "i", &res);//转换返回类型
cout << "res:" << res << endl;//输出结果
//释放
/*Py_DECREF(pClassCalc);
Py_DECREF(pInstanceCalc);
Py_DECREF(pModule);*/
Py_Finalize(); // 与初始化对应
system("pause");
return 0;
}
出现问题
1、Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named ‘encodings’
问题原因:是因为没有加载PYTHONHOME(python的安装路径)
解决方法:找到python的安装路径(cmd-“python”-“import sys”-“print(sys.path)”),然后在Py_Initialize()之前调用下Py_SetPythonHome(L"C:\\Python27")。
注意:双引号里面是python安装的只需要到最外层就可以,要使用双斜杆\\加载路径。
待更新
本文详细介绍了如何从C++环境中调用Python代码,包括运行Python脚本、调用Python函数并获取返回值,以及调用Python类的方法。文章提供了完整的代码示例,涵盖了初始化Python环境、执行Python语句、导入模块、调用函数和类,以及处理返回值的过程。
486

被折叠的 条评论
为什么被折叠?



