【问题标题】:Boost - Importing Qt created C++ Python module in PythonBoost - 在 Python 中导入 Qt 创建的 C++ Python 模块
【发布时间】:2019-02-19 15:41:05
【问题描述】:

我在 Qt Quick Application 和 Boost 中有以下代码。 在这个 Cpp 中有一个使用 BOOST_PYTHON_MODULE(hello) 创建的个人模块。主要目标是能够在 Python 中 import hello 并调用 hello struct 的方法。我的 Python 脚本只包含非常简单的结构,因为我只想在导入 hello 时看到没有错误。

import hello
print("Import was successful!")

下面的大部分代码都是从 stackoverflow 中的另一个问题复制而来的,但不完全是,所以我不得不重新发布这些部分。

Main.cpp

#include <cstdlib>  // setenv, atoi
#include <iostream> // cerr, cout, endl
#include <boost/python.hpp>

#include <QGuiApplication>
#include <QQmlApplicationEngine>


struct World
{
    void set(std::string msg) { this->msg = msg; }
    std::string greet()       { return msg;      }
    std::string msg;
};

//---------------------------------------------------------------------------------------------------------------------
/// Staticly linking a Python extension for embedded Python.
BOOST_PYTHON_MODULE(hello)
{
    namespace python = boost::python;
    python::class_<World>("World")
            .def("greet", &World::greet)
            .def("set", &World::set)
            ;
}

//---------------------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    namespace python = boost::python;
    try
    {
        int uploaded = PyImport_AppendInittab("hello", &PyInit_hello);
        //This executes else part
        if(uploaded == -1)
          std::cout<< "Module table was not extended: " << uploaded << std::endl;
        else
          std::cout<< "Module Table was extended" << std::endl;

        Py_Initialize();

    } catch (...)
    {
        PyErr_Print();
        return 1;
    }

    return app.exec();
}

最后,我运行我的 QT 应用程序,return app.exec(); 在我尝试从终端运行上面提到的 python 脚本时使其保持运行。 python 脚本与当前运行的应用程序位于同一目录中,不确定是否有任何区别。

那么我得到的错误是:

Traceback (most recent call last):
  File "test_hilton.py", line 1, in <module>
    import hello
ModuleNotFoundError: No module named 'hello'

不确定我在这里缺少什么。根据 Python API:

PyImport_AppendInittab - 将单个模块添加到现有的表中 内置模块。这是一个方便的包装 PyImport_ExtendInittab(),如果表不能被返回 -1 扩展。新模块可以通过名称 name 导入,并使用 函数 initfunc 作为在 第一次尝试导入。

并且 main 中 try-catch 块中的 If-else 部分证明了 hello 模块正在被添加到表中。出于对做什么的想法,在不同的地方看了看。但仍然坚持这部分问题。

【问题讨论】:

    标签: python c++ qt boost


    【解决方案1】:

    由于hello 模块是在该Qt 程序中定义的,因此它仅在该程序中可用。在通过import hello 导入 hello 时,执行该程序不会使其对期望找到hello.pyhello.so(文件扩展名可能因操作系统而异)的python 解释器可用。

    您需要构建一个 python 模块,answer 可能会有所帮助。

    【讨论】:

    • 几个小时后我想通了。我意识到我的交流应该是实时的。在我的情况下,在 C++ 中添加 python 也是不可能的。然后过了一段时间我意识到我应该只使用 IPC。现在我正在使用:ZeroMQ,效果很好!感谢您的确认。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 2011-07-07
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多