从C / C ++调用Python函数

时间:2014-04-19 23:26:12

标签: c++ c python-2.7

我试图调用一个简单的python函数,它在(“ctest.py”)中定义为

def square(a)
    return a**2

以下(“pytest.c”)(在同一目录中)是我试图用来调用该函数的C代码。我遇到的问题是当C程序尝试加载python模块时返回NULL。

#include <Python.h>

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; 
}

C代码构建于:

 gcc -o pytest -lpythhon2.7 -I/usr/include/python2.7 pytest.c

1 个答案:

答案 0 :(得分:0)

看起来您遇到了命名/路径问题。

你可能会看看这个答案: Why does PyImport_Import fail to load a module from the current directory?