【发布时间】: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 模块正在被添加到表中。出于对做什么的想法,在不同的地方看了看。但仍然坚持这部分问题。
【问题讨论】: