c++调用python脚本

直接上代码

#include <iostream>
#ifdef WIN32
#include "Python.h"
#else
#include "/usr/local/include/python2.7/Python.h"
#endif
//如果是在windows-mingw-python2.7环境下,需要在工程->设置->Include和lib设置python2.7的路径,
//并在“链接 ”的参数中添加-Lc:\Python27\libs -lpython27

//如果是在linux环境下,则用下面命令进行编译链接 
//g++ PythonTest.cpp -I/usr/local/include/python2.7 -L/usr/local/lib/python2.7 -lpython2.7 -lpthread -ldl -lm -lutil -o test

using namespace std;

int main(int argc, char** argv)
{
//python初始化 
    Py_Initialize();
    if(!Py_IsInitialized())
    {
        printf("Py_Initialize() Error!\n");
        return -1;
    }
//只有在linux下才需要指定路径
#ifndef WIN32
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
#endif
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs;
//载入module 
    pName = PyString_FromString("pytest");
    pModule = PyImport_Import(pName);

    if(!pModule)
    {
        printf("Can't find pytest.py");
        getchar();
        return -1;
    }
  //将module中的方法以字典形式读入
    pDict = PyModule_GetDict(pModule);
    if(!pDict)
    {
        printf("PyModule_GetDict Error!\n");
        return -1;
    }
//在方法字典中通过名字获取对应的方法
    pFunc = PyDict_GetItemString(pDict, "add");
    if(!pFunc || !PyCallable_Check(pFunc))
    {
        printf("Can't find function[add]\n");
        getchar();
        return -1;
    }

//设置方法的参数 
    *pArgs;
    pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("f", 3.1));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("f", 4.3));
//调用方法add,传入参数 float
    PyObject_CallObject(pFunc, pArgs);

//调用方法foo,传入参数int 
    pFunc = PyDict_GetItemString(pDict, "foo");
    if(!pFunc || !PyCallable_Check(pFunc))
    {
        printf("Can't find function [foo]\n");
        getchar();
        return -1;
    }

    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 3));

    PyObject_CallObject(pFunc, pArgs);
    
//调用方法hello,传入参数string
    pFunc = PyDict_GetItemString(pDict, "hello");
    if(!pFunc || !PyCallable_Check(pFunc))
    {
        printf("Can't find function [hello]\n");
        getchar();
        return -1;
    }
    pArgs = PyTuple_New(1); 
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", "World"));
    
    PyObject_CallObject(pFunc, pArgs);
    

//释放之前的变量 
    Py_DECREF(pName);
    Py_DECREF(pArgs);
    Py_DECREF(pModule);
//python调用结束 
    Py_Finalize();
    return 0;
}


Makefile文件
PYTHON_INCLUDE_FLAGS = \
        -I/usr/local/include/python2.7

LIB_FLAGS = \
        -L/usr/local/lib/python2.7 -lpython2.7 -lpthread -ldl -lm -lutil
SOURCE = \
        PythonTest.cpp
all:${SOURCE}
        g++ $(PYTHON_INCLUDE_FLAGS) $(SOURCE) ${LIB_FLAGS} -o test
clean:
        rm -f test *.o *.out

 

 
posted @ 2012-07-04 23:19  Geek_Ma  阅读(2167)  评论(0编辑  收藏  举报