- 本文主要实现在linux环境下编写cpp文件调用python文件中的模块
代码块
#include "Python.h"
#include <iostream>
using namespace std;
int main(){
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject * pName = NULL;
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
PyObject * pDict = NULL;
pName = PyString_FromString("hello");
pModule = PyImport_Import(pName);
if(!pModule){
cout << "加载模块失败" << endl;
}
pDict = PyModule_GetDict(pModule);
if(!pDict){
cout << "加载dict失败" << endl;
}
pFunc= PyDict_GetItemString(pDict, "hello");
if(!pFunc){
cout << "加载函数失败" << endl;
}
PyObject * args = PyTuple_New(1);
PyTuple_SetItem(args, 0, Py_BuildValue("s","Cattie"));
PyObject * pRet = PyEval_CallObject(pFunc, args);
if(pRet){
long result = PyInt_AsLong(pRet);
cout << "result:" << result;
}
Py_Finalize();
}
def hello(name):
print("hello, %s" %name)
return 123
# g++ hello.cpp -I/usr/local/include/python2.7 -ldl -lutil -lpthread -lpython2.7 -o hello
- 结果