我试图调用一个简单的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

您似乎遇到了命名/路径问题。

您可能会看到以下答案: 为什么PyImport_Import无法从当前目录加载模块?

  ask by user3552845 translate from so

未解决问题?本站智能推荐: