C++调用Python模块

来源:互联网 发布:淘宝二手ps4主机能买吗 编辑:程序博客网 时间:2024/05/19 19:32
  • 本文主要实现在linux环境下编写cpp文件调用python文件中的模块

代码块

  • c++/hello.cpp
    #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(); // 释放资源    }
  • python/hello.py
    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
  • 结果
    这里写图片描述
原创粉丝点击