vs2013中C++调用Python3.5的方法

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


using namespace std;

int main()
{
string path = "D:/python_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("h");
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();
system("pause");
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值