一 开发环境配置
先安装python, 自行百度。安装ok后,在安装目录会有python的C头文件,lib,dll, 这些在写C++程序时都会用到。
我用的是Python3.7,在VS2015中项目属性配置Python的头文件,库文件
(1)包含python的头文件:右键项目属性---C/C++ --- 常规 ---- 附加包含目录
(2)包含lib
添加头文件 #include "Python.h“
加载静态库 #pragma comment(lib, "python37.lib")
把Hello.py放到程序当前路径, 两个函数,用Pythton写的加法和减法函数。
''''
简单的Python程序
'''
def Add(a, b):
c = a + b
return c
def Sub(a, b):
c = a - b
return c
C++ 代码如下:
/*
C++ 程序如何调用Pyhton程序
*/
#include "stdafx.h"
#include
#include "Python.h"
using namespace std;
//导入python静态库
#pragma comment(lib, "python37.lib")
int main()
{
PyObject* pName = NULL;
PyObject* pModule = NULL;
PyObject* pDict = NULL;
PyObject* pFunc = NULL;
PyObject* pArgs = NULL;
PyObject* pRet = NULL;
// 1 初始化Python, 在使用Python系统前,必须使用Py_Initialize对其进行初始化;
Py_Initialize();
// 2 检查初始化是否成功, 返回0初始化失败
int nRet = Py_IsInitialized();
if (nRet == 0)
{
cout
关注
打赏