• 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 "); 
             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" 

  • 相关阅读:
    Linux网络编程入门 (转载)
    linux库文件编写入门(笔记)
    动态库封装参考模板
    c++中的 extern "C"(转载)
    Python网络爬虫学习总结
    Google发布机器学习术语表 (包括简体中文)
    NoSQL 简介
    TCP和UDP的区别?
    UDP和TCP的主要特点
    2017中国互联网企业百强
  • 原文地址:https://www.cnblogs.com/jkred369/p/7406123.html
Copyright © 2020-2023  润新知