1. 程式人生 > >vs2013中C++呼叫Python3.5的方法

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;
}