1. 程式人生 > >C 語言調用python 腳本函數

C 語言調用python 腳本函數

string 2.7 + - rsize 加載 -o func buffer ios

剛好幾個月前做過,C++ 函數裏面先加載python 腳本,再調用 裏面的 def 函數,我把代碼貼出來,你在main 函數裏面,調用getDataByScript 函數,另外相同目錄下放一個 fuckTest.py ,我是centos6.7
編譯
g++ -o test test.cpp -lpython2.7


callPython.h
#include<Python.h>
#include<string>
using namespace std;

char* getDataByScript(const char* moduleName,int& bufferSize,int& errInfo)
{
errInfo = 0;
bufferSize = 0;
Py_Initialize();
if(!Py_IsInitialized())
{
errInfo = 1;
return NULL;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.insert(0,‘./‘)");
//PyRun_SimpleString("print sys.path");
PyObject* pName = PyString_FromString(moduleName);
PyObject* pModule = PyImport_Import(pName);
if(!pModule)
{
printf("can‘t import error\n");
errInfo = 2;
return NULL;
}
PyObject* pDict = PyModule_GetDict(pModule);
if(!pDict)
{
errInfo = 3;
return NULL;
}

PyObject* pFunc = PyDict_GetItemString(pDict,"callFuncNoArgs");
if(!pFunc || !PyCallable_Check(pFunc))
{
errInfo = 4;
return NULL;
}
//PyObject* pArgs = PyTuple_New(2);
//PyTuple_SetItem(pArgs,0,Py_BuildValue("l",100));
//PyTuple_SetItem(pArgs,1,Py_BuildValue("l",200));
PyObject* res = PyObject_CallObject(pFunc,NULL);
if(!PyString_Check(res))
{
errInfo = 5;
return NULL;
}
else
{
bufferSize = int(PyString_Size(res));
return (char*)PyString_AsString(res);
}
}


test.cpp

#include <iostream>
#include"callPython.h"
using namespace std;
int main()
{
int size =0;
int errInfo = 0;
getDataByScript("fuckTest",size,errInfo);
return 0;
}

fuckTest.py

def callFuncNoArgs():
print "test.py func called !!!"
return "fuck"

C 語言調用python 腳本函數