title: Call Python function from C/C++
body: <p>I am trying to call a simple python function which is defined in ("ctest.py") as</p>
  
  <pre><code>def square(a)
      return a**2
  </code></pre>
  
  <p>the following ("pytest.c") (in same directory) is the C code that I am trying to use to call the function. The issue that I am experiencing is that when the C program tries to load the python module NULL is returned.</p>
  
  <pre><code>#include &lt;Python.h&gt;
  
  int main(int argc, char* argv[])
  {
    printf("Calling Python Function\n");
    Py_Initialize();  // Initialize the Python interpreter.
  
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;  // Create some Python       objects that will later be assigned values.
    // Convert the file name to a Python string.
    pName = PyString_FromString("ctest.py");
    if (pName==NULL)
       printf("file not found");
    else
      printf("%s\n", PyString_AsString(pName));
    // Import the file as a Python module.
    pModule = PyImport_Import(pName);         //PROBLEM LINE
    if(pModule==NULL) 
       printf("no Module\n");
    // Create a dictionary for the contents of the module.
    pDict = PyModule_GetDict(pModule);
    printf("After Dictionary retrieval\n");
    // Get the add method from the dictionary.
    pFunc = PyDict_GetItemString(pDict, "square");
    printf("after function retrieval\n");
  
    // Convert 2 to a Python integer.
    pValue = PyInt_FromLong(2);
    // Call the function with the arguments.
    PyObject* pResult = PyObject_CallObject(pFunc, pValue);
    // Print a message if calling the method failed.
    if(pResult == NULL)
      printf("Calling the add method failed.\n");
    // Convert the result to a long from a Python object.
    long result = PyInt_AsLong(pResult);
    // Destroy the Python interpreter.
    Py_Finalize();
    // Print the result.
    printf("The result is %d.\n", result);
    return 0; 
  }
  </code></pre>
  
  <p>The C Code is built with:</p>
  
  <pre><code> gcc -o pytest -lpythhon2.7 -I/usr/include/python2.7 pytest.c
  </code></pre>