VS平台简单的使用C++调用Python3.5的方法

创建C++控制台工程,工程属性中需要添加python的头文件和库文件路径,我是通过搜索找到文件位置的


头文件路径C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\include;

库文件路径C:\Users\Administrator\AppData\Local\Programs\Python\Python35-32\libs;


创建一个简单的python加法功能模块,文件名为Insert.py


def _add(x, y):
    print('add', x, 'and', y)
    return x + y

C++代码如下


// Python_Insert.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <python.h>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	string path = "F:/python/project/test";  //python文件路径
	string chdir_cmd = string("sys.path.append(\"");

	//初始化Python环境
	Py_Initialize();

	chdir_cmd += path;
	chdir_cmd += "\")";

	//PyRun_SimpleString("")可以简单的直接运行字符串内的Python语句
	const char* cstr_cmd = chdir_cmd.c_str();
	PyRun_SimpleString("import sys");
	//添加Insert模块路径
	PyRun_SimpleString(cstr_cmd);

	//导入模块
	PyObject* pModule = PyImport_ImportModule("Insert");

	if (!pModule)
	{
		cout<<"Python get module failed." << endl;
		return 0;
	}

	cout << "Python get module succeed." << endl;

	//获取Insert模块内_add函数
	PyObject* pv = PyObject_GetAttrString(pModule, "_add");
	if (!pv || !PyCallable_Check(pv))
	{
		cout << "Can't find funftion (_add)" << endl;
		return 0;
	}
	cout << "Get function (_add) succeed." << endl;

	//初始化要传入的参数,args配置成传入两个参数的模式
	PyObject* args = PyTuple_New(2);
	//将Long型数据转换成Python可接收的类型
	PyObject* arg1 = PyLong_FromLong(4);
	PyObject* arg2 = PyLong_FromLong(3);

	//将arg1配置为arg带入的第一个参数
	PyTuple_SetItem(args, 0, arg1);
	//将arg1配置为arg带入的第二个参数
	PyTuple_SetItem(args, 1, arg2);

	//传入参数调用函数,并获取返回值
	PyObject* pRet = PyObject_CallObject(pv, args);

	if (pRet)
	{
		//将返回值转换成long型
		long result = PyLong_AsLong(pRet);
		cout << "result:" << result;
	}

	Py_Finalize();

	return 0;
}


运行结果



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值