准备python脚本
def Hello():
print("hello world!")
def add(x,y):
print("add",x,"and",y)
return x+y
- 包含目录中增加Python的include目录
- 库目录增加Python的libs目录
- 链接器>输入中增加附加依赖项即pythonxx.lib,其中xx文版本号
C++文件
#include <iostream>
#include "include/Python.h"
using namespace std;
int main()
{
//Py_SetPythonHome(L"./"); 打包时设置解释器路径
//如果不设置需要在环境变量中增加 pythonhome和pythonpath
//一定要重启
Py_Initialize();
cout << "初始化成功" << endl;
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject* pModule = PyImport_ImportModule("mytest");
if (!pModule)
{
cout << "Python get module failed." << endl;
return 0;
}
PyObject* pFunc = NULL;
pFunc = PyObject_GetAttrString(pModule, "Hello");
//PyEval_CallObject(pFunc, NULL);//调用
PyObject_CallObject(pFunc, NULL); //调用
//获取add函数
PyObject* pAdd = PyObject_GetAttrString(pModule, "add");
if (!pAdd ||!PyCallable_Check(pAdd))
{
cout << "Python get add failed." << endl;
return 0;
}
//初始化要传入的参数
PyObject* args = PyTuple_New(2);
//将Long类型转为Python可接受的类型
PyObject* arg1 = PyLong_FromLong(4);
PyObject* arg2 = PyLong_FromLong(3);
//将arg1配置为arg带入第一参数
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);
PyObject* pRet = PyObject_CallObject(pAdd, args); //调用
if (pRet)
{
long result = PyLong_AsLong(pRet);
cout << "result:" << result << endl;
}
Py_Finalize();
system("pause");
}