C++——引入python函数
1、添加环境
#include<Python.h>
2、添加库路径
3、函数剖析
//初始化python解释器
void Py_Initialize(void);
//检查是否初始化成功
int Py_IsIntialized(void);
//导入python模块
PyObject* PyImport_ImportModule(char *name);
//执行Python代码
int PyRun_SimpleString(const char *command);
//构建参数列表, 把C类型转化成Python支持类型
PyObject* Py_BuildValue(char* format, ...)
//储存python导入的方法字典
PyModule_GetDict
//获取方法
PyObject* PyDict_GetItemString(PyObject*, const char*);
4、实例运用
如下有一个temp.py(pyhon文件)
def hello(name):
print("hello world, ", name)
return 0
#include <Python.h>
void importPython()
{
PyObject *pName = NULL;
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyObject *pDict = NULL;
PyObject *pArgs = NULL;
Py_Initialize();
if(!Py_IsInitialized())
{
cout << "python initialized failed." << endl;
}
// 载入名为PyPlugin的脚本
//添加路径为当前文件夹
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//导入python文件
pModule = PyImport_ImportModule("getfiles");
if (!pModule)
{
printf("can't getfiles.py\n");
}
pDict = PyModule_GetDict(pModule);
if(!pDict)
{
cout << "can't pDict" << endl;
system("pause");
return;
}
pFunc = PyDict_GetItemString(pDict, "hello");
if(!pFunc || !PyCallable_Check(pFunc))
{
cout << "can't findfunction run" << endl;
system("pause");
return;
}
char name[100] = "coco567";
//将参数保存在容器内
PyObject *list = PyList_New(0);
pArgs = PyTuple_New(1);
//s对应string类型
PyList_Append(list, Py_BuildValue("s", name));
PyTuple_SetItem(pArgs, 0, list);
#调用
PyObject *pRet = PyEval_CallObject(pFunc, pArgs);
int ret = 0;
if(pRet && PyArg_ParseTuple(pRet, "i", &ret))
{
printf("Function iter_reader call successful ret = %d\n", ret);
}
//垃圾回收
if(pArgs)
Py_DECREF(pArgs);
if(pFunc)
Py_DECREF(pFunc);
//关闭解释器
Py_Finalize();
}