C 语言调用python 脚本函数

刚好几个月前做过,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" 

转载于:https://www.cnblogs.com/jkred369/p/7406123.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值