您当前的位置: 首页 >  Python

令狐掌门

暂无认证

  • 0浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++调用Python

令狐掌门 发布时间:2020-02-29 23:59:06 ,浏览量:0

一 开发环境配置

   先安装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             
关注
打赏
1652240117
查看更多评论
0.0375s