在c/c++中调用Python

1.牛刀小试

#include <Python.h>

int main() {
  Py_Initialize();

  PyRun_SimpleString("import sys");
  PyRun_SimpleString("print sys.version");


  return 0;
}

编译命令

  g++ -I/usr/include/python2.6 -L/usr/lib/python2.6 -lpython2.6  test.cpp -o test.out。其中-I(第一个编译选项)指的是头文件(Python.h)所在路径。-L指的是加载的动态库所在路径(不包括文件名)。-l(第三个编译路径)指的是动态库的文件名。

 

2.渐入佳境

  
std::string static_scan_files(const char *filepath, const char* filetype, int digital_flag, int office_flag)
{
    PyObject * pModule = NULL;      
    PyObject * pFunc = NULL;

    Py_Initialize();

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./OfficeAndPESig/')"); //进入到当前目录下的子目录,子目录的名称为OfficeAndPESig
 
    pModule =PyImport_ImportModule("app_static"); // 导入子目录下app_static.py的文件
    if(!pModule)
        printf("app_static module is not found\n");
    pFunc= PyObject_GetAttrString(pModule, "get_file_info"); //加载get_file_info的函数
    if(!pModule)
        printf("app_static module's get_file_info is not found\n");

    PyObject *pArgs = PyTuple_New(4); //执行形参空间,下面是填入对应的参数
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", filepath));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("s", filetype));
    PyTuple_SetItem(pArgs, 2, Py_BuildValue("i", digital_flag));
    PyTuple_SetItem(pArgs, 3, Py_BuildValue("i", office_flag));


    PyObject *pReturn = NULL;  
    pReturn = PyEval_CallObject(pFunc, pArgs); //执行函数并得到返回值
    if(!pModule)
        printf("call python function error\n");

    char *result = NULL;
    PyArg_Parse(pReturn, "s", &result);

    Py_Finalize();

    return std::string(result);
}

该例子为如何通过函数来调用Python文件中的函数,并得到返回值。



posted @ 2018-07-27 18:25  ly-bnu  阅读(360)  评论(0)    收藏  举报