[C++-sig] failed in PyImport_Import()

Shrikant Chikhalkar shrikantvc at gmail.com
Thu Oct 25 08:52:24 CEST 2007


Hi,

i am tring to call python function from 'C' program. i get NULL value return
by PyImport_Import()

following is the code. code is copied from
http://www.codeproject.com/cpp/embedpython_1.asp

following file is saved as

call_function.c

/************************************************************************************************************/

// call_function.c - A sample of calling
// python functions from C code
//
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

    if (argc < 3)
    {
        printf("Usage: exe_name python_source function_name\n");
        return 1;
    }

    // Initialize the Python Interpreter
    Py_Initialize();

    // Build the name object
    pName = PyString_FromString(argv[1]);

    // Load the module object
    pModule = PyImport_Import(pName);

    // pDict is a borrowed reference
    pDict = PyModule_GetDict(pModule);

    // pFunc is also a borrowed reference
    pFunc = PyDict_GetItemString(pDict, argv[2]);

    if (PyCallable_Check(pFunc))
    {
        PyObject_CallObject(pFunc, NULL);
    } else
    {
        PyErr_Print();
    }

    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Finish the Python Interpreter
    Py_Finalize();

    return 0;
}

/************************************************************************************************************/
python file saved as

py_function.py

/************************************************************************************************************/

'''py_function.py - Python source designed to '''
'''demonstrate the use of python embedding'''

def multiply():
    c = 12345*6789
    print 'The result of 12345 x 6789 :', c


    return c

/************************************************************************************************************/

$gcc -g call_function.c  -lpython2.5 -ocall_function
$./call_function py_function.py multiply

i get following output

ImportError: No module named py_function
Failed to load "py_function"

when i kdbg(debug) it i vet NULL value returned from PyImport_Import()..

can any one please find out the error that i am doing.

-- 
Shrikant
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20071025/e3ca2dfd/attachment.htm>


More information about the Cplusplus-sig mailing list