Simple Example How To Call Python Function in C/C++

13,188

Solution 1

You most likely have not installed python dev tools, i.e. python.h is never found. Locate python.h and look for compile errors and repost if there are some.

Edit: This is old info. Including should be as easy as adding the include directory to the include directories, see: How do I get Visual Express 2010 to find my python.h header file?

Solution 2

Here's some code from a question I asked. This should do what you want.

Args: argv[1] contains the path to your .py file argv[2] contains the name of the function you want to call

int wmain(int argc, wchar_t** argv)
{
    PyObject* py_imp_str;
    PyObject* py_imp_handle;
    PyObject* py_imp_dict; //borrowed
    PyObject* py_imp_load_source; //borrowed
    PyObject* py_dir; //stolen
    PyObject* py_lib_name; //stolen
    PyObject* py_args_tuple;
    PyObject* py_lib_mod;
    PyObject* py_func;
    PyObject* py_ret;

    Py_Initialize();

    //import our python script using the imp library (the normal import doesn't allow you to grab py files in random directories)
    py_dir = PyUnicode_FromWideChar(argv[1], wcslen(argv[1]));
    py_imp_str = PyString_FromString("imp");
    py_imp_handle = PyImport_Import(py_imp_str); //normal python import for imp
    py_imp_dict = PyModule_GetDict(py_imp_handle); //borrowed
    py_imp_load_source = PyDict_GetItemString(py_imp_dict, "load_source"); //borrowed
    py_lib_name = PyUnicode_FromWideChar(argv[2], wcslen(argv[2]));

    //setup args for imp.load_source
    py_args_tuple = PyTuple_New(2);
    PyTuple_SetItem(py_args_tuple, 0, py_lib_name); //stolen
    PyTuple_SetItem(py_args_tuple, 1, py_dir); //stolen

    //call imp.load_source
    py_lib_mod = PyObject_CallObject(py_imp_load_source, py_args_tuple);
    py_lib_mod_dict = PyModule_GetDict(py_lib_mod); //borrowed

    //get function object
    py_func = PyDict_GetItem(py_lib_mod_dict, py_lib_name);
    //call function object
    py_ret = PyObject_CallFunction(py_func, NULL);

    if (py_ret)
    {
        printf("PyObject_CallFunction from wmain was successful!\n");
        Py_DECREF(py_ret);
    }
    else
        printf("PyObject_CallFunction from wmain failed!\n");

    Py_DECREF(py_imp_str);
    Py_DECREF(py_imp_handle);
    Py_DECREF(py_args_tuple);
    Py_DECREF(py_lib_mod);

    Py_Finalize();

    fflush(stderr);
    fflush(stdout);
    return 0;
}

If you haven't found this already, the following link describes the C interface to Python. Very handy: http://docs.python.org/2/c-api/index.html

Share:
13,188
Yoshua Joo Bin
Author by

Yoshua Joo Bin

Updated on June 04, 2022

Comments

  • Yoshua Joo Bin
    Yoshua Joo Bin almost 2 years

    i have already searched through google, and many refence, but i only see a complex example of coding, would you give me an example (In Simple Code) so i can understand. I've already code it, but it breaks everytime i run it Here's the code

    #include <Python.h>
    int main()
    {
      PyObject *pName, *pModule, *pDict, *pFun, *pValue;
      // Initialize the Python Interpreter
      Py_Initialize();
     // Build the name object
     pName = PyString_FromString("C:\\Documents and Settings\\MASTER\\My Documents\\Visual Studio       2010\\Projects\\Python\\Test.py");
    if(pName)printf("OK");
    
    // Load the module object
    pModule = PyImport_Import(pName);
    
    // pDict is a borrowed reference 
    pDict = PyModule_GetDict(pModule);
    
    // pFunc is also a borrowed reference 
    pFun = PyDict_GetItemString(pDict, "prinTname");
    
    if (PyCallable_Check(pFun)) 
    {
        PyObject_CallObject(pFun, NULL);
    } else 
    {
        PyErr_Print();
    }
    
    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);
    
    Py_DECREF(pDict);
    Py_DECREF(pFun);
    // Finish the Python Interpreter
    Py_Finalize();
    getchar();
    return 0;
    }
    

    and there are some messages First-chance exception at 0x1e00503b in Python.exe: 0xC0000005: Access violation reading location 0x00000004. Unhandled exception at 0x1e00503b in Python.exe: 0xC0000005: Access violation reading location 0x00000004. The program '[4548] Python.exe: Native' has exited with code 0 (0x0).