小编agr*_*fft的帖子

PyObject_GetAttrString C++ 函数返回 NULL:无法从 C++ 调用 Python 函数

我刚刚开始使用 Python 和 C++ 工作,我对为什么无法从 C++ 调用 Python 中的函数感到有点困惑。

这是我当前的 C++ 测试代码:

      #include <iostream>
      #include <Python.h>
      using namespace std;

      int main()
      {
             Py_Initialize();
             PyObject* myModuleString = PyString_FromString("test");
             PyObject* myModule       = PyImport_Import(myModuleString);

             if( myModule )
             {
                      PyObject* myFunction     = PyObject_GetAttrString(myModule, "Hello");
                      if( myFunction )
                      {
                             PyEval_CallObject( myFunction, NULL );
                      }
                      else
                      {
                             fprintf( stderr, "myFunction is NULL" );
                      }
             }
             else
             {
                      fprintf( stderr, "myModule is NULL" );
             }

             Py_Finalize();
             cin.get();
             return 0;
      }
Run Code Online (Sandbox Code Playgroud)

这是我的 test.py Python 代码:

      import sys

      def …
Run Code Online (Sandbox Code Playgroud)

c++ python python-2.7

5
推荐指数
1
解决办法
4722
查看次数

标签 统计

c++ ×1

python ×1

python-2.7 ×1