python - PyObject_GetAttrString C++ 函数返回 NULL : Unable to call Python functions from C++

标签 python c++ python-2.7

我刚刚开始使用 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;
      }

这是我的 test.py Python 代码:

      import sys

      def Hello():
            print "Hello, world!"

之前我有一个更复杂的测试,但是我遇到了PyObject_GetAttrString传回NULL的问题,所以我想做一个更简单的测试,我在调用PyObject_GetAttrString后仍然收到NULL。根据我的理解,PyObject_GetAttrString 将 PyObject* 传递给函数,然后我调用它,因此在那里接收 NULL 基本上意味着我无法调用该函数。

是的,我看过https://docs.python.org/2.7/甚至测试了 https://docs.python.org/release/2.6.5/extending/embedding.html#pure-embedding 的步骤 5.3 中给出的示例(我正在使用 2.7.7,因为我打算与 3ds Max 集成)。它仍然遇到与 PyObject_GetAttrString 相同的问题。

我假设这是一个简单的错误或我在 C++ 或 Python 代码中遗漏的步骤。

最佳答案

将 Python 脚本名称从 test.py 更改为对我有用的任何其他名称。

关于python - PyObject_GetAttrString C++ 函数返回 NULL : Unable to call Python functions from C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24313681/

相关文章:

python - Flask-socketio - 无法设置 "Access-Control-Allow-Origin"响应 header

Python:通过xpath获取html表格数据

c++ - 如何为回调函数分配参数

django - 如何修复我的 Django ImproperlyConfigured 异常?

python - 电影加载但在 pygame 中却没有电影声音

python - Pygame:位 block 传输移动背景会产生太多模糊

python - azure 批处理网络配置 -> "failed to authenticate"

c++ - C3409 : empty attribute block is not allowed by noreturn

c++ - 在 32 位 Linux 上编译代码时出现未声明错误 'gtk_window_set_keep_above'

Python 更改接口(interface) channel