创建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;
}
运行结果