1. 基础环境
Win10\VS2019\Python38
2.首先定义一个Python函数,确保运行OK的;
# _*_ coding:utf-8 _*_
import base64
def Helloword():
print('hello word !')
3.VS属性配置
(一定要注意base_environment,如果python是64位的,vs调试环境一定要保持一致!!!)
图1.vs项目属性配置步骤图;
图2. vs项目属性配置步骤图;
注意(图2所示):
链接器->输入->附加依赖项
debug(x84: python安装目录/libs/python38_d.lib;
release(x64): python安装目录/libs/python38.lib;
图3. Python文件路径图
注意:Pyhton文件需要置于项目文件夹下;
3. 编写C++调用程序;
#include<iostream>
#include<string>
#include<python.h>
using namespace std;
int main()
{
// 初始化python解释器,C++调用Python之前必须先初始化解释器;;
Py_Initialize();
//判断初始化是否完成:
if (!Py_IsInitialized())
{
printf("Initialized failed");
return 0;
}
//添加Insert模块路径;
//PyRun_SimpleString(chdir_cmd.c_str());
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//导入模块,调用文件;
PyObject* pModule = PyImport_ImportModule("helloword");
if (!pModule)
{
cout << " call module failed. " << endl;
return 0;
}
cout << " call module successfully ! " << endl;
//声明变量,初始化;
PyObject * pFunc = NULL;
//调用函数名;
pFunc = PyObject_GetAttrString(pModule, "Helloword");
PyEval_CallObject(pFunc, NULL);
Py_Finalize();
system("pause");
return 0;
}
4. 运行结果如图4所示:
图4 . C++调用Python函数运行结果图
5. 欢迎大家交流讨论!