LINUX.ORG.RU

История изменений

Исправление shaplov, (текущая версия) :

Оказалось, что я не правильного консультанта исходно выбрал ;-) Надо было смотреть на https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly

Добавил недостающий sys.modules[module_name] = module переведенный на boost::python’овскую нотацию, и все заработало.

Итого правильный ответ:

#include <boost/python.hpp>
#include <stdio.h>


int main()
{
        Py_InitializeEx(0);

        try {
                boost::python::object modImpUtil = boost::python::import("importlib.util");
                boost::python::object modSys = boost::python::import("sys");

                PyImport_AddModule("test_module");

                boost::python::object spec = modImpUtil.attr("spec_from_file_location")("test_module", "test_module.py");
                boost::python::object mod = modImpUtil.attr("module_from_spec")(spec);
                spec.attr("loader").attr("exec_module")(mod);
                modSys.attr("modules")["test_module"] = mod;

                boost::python::exec("test_out(\"Hello, World!\")", boost::python::import("test_module").attr("__dict__"));
        }
        catch (const boost::python::error_already_set&)
        {
                PyErr_Print();
        }
        Py_Finalize();
}

Исходная версия shaplov, :

Оказалось, что я не правильного консультанта исходно выбрал ;-) Надо было смотреть на https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly

Добавил недостающий sys.modules[module_name] = module переведенный на boost::python’овскую нотацию, и все заработало. Итого правильный ответ:

#include <boost/python.hpp>
#include <stdio.h>


int main()
{
        Py_InitializeEx(0);

        try {
                boost::python::object modImpUtil = boost::python::import("importlib.util");
                boost::python::object modSys = boost::python::import("sys");

                PyImport_AddModule("test_module");

                boost::python::object spec = modImpUtil.attr("spec_from_file_location")("test_module", "test_module.py");
                boost::python::object mod = modImpUtil.attr("module_from_spec")(spec);
                spec.attr("loader").attr("exec_module")(mod);
                modSys.attr("modules")["test_module"] = mod;

                boost::python::exec("test_out(\"Hello, World!\")", boost::python::import("test_module").attr("__dict__"));
        }
        catch (const boost::python::error_already_set&)
        {
                PyErr_Print();
        }
        Py_Finalize();
}