C语言调用python代码

时间:2022-09-09 19:57:14

出处:http://outofmemory.cn/code-snippet/5589/C-language-call-python-code

//#========================================================
//#              author:ago                                
//#              2012/08/24 19:26:57                  
//#========================================================
#include "python_lib/Python.h"
#include <windows.h>
#pragma comment(lib,"python27_d.lib")

int main(int argc, char *argv[])
{
    Py_Initialize();

    //PyRun_SimpleString("import sys");
    //PyRun_SimpleString("sys.path.append('./')");
    PyObject* pName = PyString_FromString("main");
    //python 文件的名字
    PyObject* pModule = PyImport_Import(pName);
    if ( !pModule )
    {
        MessageBox(NULL, ("找不到main.py"), ("提示"), MB_OK);
        return 1;
    }
    PyObject* pDict = PyModule_GetDict(pModule);
    PyObject* pFunc = PyDict_GetItemString(pDict, "test"); 
    //python 文件中函数名:test
    PyObject_CallObject(pFunc, NULL);
    Py_Finalize();
    system("pause");
}