从 boost::p ython::exec( 任何内容)调用时崩溃

Crash on call from boost::python::exec( anything )

本文关键字:调用 崩溃 任何内 boost ython exec      更新时间:2023-10-16

我正在尝试在我的程序中实现一些Python的东西,我决定使用Boost::P ython,所以我根据说明编译它,使用bjam,使用mingw/gcc,获取dlls和.a文件
我为此使用了 Code::Blocks,所以我将 dll 放在我项目的工作目录中,我使用的其余 dll 在哪里,并决定运行boost::python::exec("b = 5");
我立刻崩溃了。想法?

#include <boost/python.hpp>
float func(int a)
{
  return a*a-0.5;
}
BOOST_PYTHON_MODULE(test_module)
{
  using namespace boost::python;
  def("func", func);
}
int main()
{
  //Try one
  boost::python::exec("b = 5");
  //Crash
  //Try two
  Py_Initialize();
  boost::python::exec("b = 5");
  //Works fine
  //Try three
  Py_Initialize();
  boost::python::exec("import test_module");
  //Throws boost::python::error_already_set and crashes
  /*
    Something along the lines of
    boost::python::exec("import test_modulen"
                        "var = test_module.func( 3 )n");
  */    
}

在项目的构建选项部分下,我添加了要链接libboost_python3-mgw48-d-1_54.dlllibpython33,以便对其进行编译。
想法?

当嵌入 Python 时,几乎所有对 Python 或 Boost.Python 的调用都应该在使用 Py_Initialize() 初始化解释器之后进行。 尝试在初始化之前调用解释器(例如使用 boost::python::exec() )将导致未定义的行为。

虽然这确定了崩溃的来源,但有一些微妙的细节可以实现嵌入Python和模块的最终目标,然后exec导入嵌入式模块。

  • 导入模块时,Python 会先检查该模块是否为内置模块。 如果模块不是内置模块,那么 Python 会尝试根据模块名称加载库,并期望库提供一个将初始化模块的函数。 由于嵌入了test_module,因此需要显式添加其初始化,以便import搜索内置模块时可以找到它。
  • import语句使用 __import__ 函数。 这个函数需要在exec的全局变量中可用。

下面是一个完整的示例,演示如何实现此目的:

#include <boost/python.hpp>
float func(int a)
{
  return a*a-0.5;
}
BOOST_PYTHON_MODULE(test_module)
{
  using namespace boost::python;
  def("func", func);
}
// Use macros to account for changes in Python 2 and 3:
// - Python's C API for embedding requires different naming conventions for
//   module initialization functions.
// - The builtins module was renamed.
#if PY_VERSION_HEX >= 0x03000000
#  define MODULE_INIT_FN(name) BOOST_PP_CAT(PyInit_, name)
#  define PYTHON_BUILTINS "builtins"
#else
#  define MODULE_INIT_FN(name) BOOST_PP_CAT(init, name)
#  define PYTHON_BUILTINS "__builtin__"
#endif
int main()
{
  // Add the test_module module to the list of built-in modules.  This
  // allows it to be imported with 'import test_module'.
  PyImport_AppendInittab("test_module", &MODULE_INIT_FN(test_module));
  Py_Initialize();
  namespace python = boost::python;
  try
  {
    // Create an empty dictionary that will function as a namespace.
    python::dict ns;
    // The 'import' statement depends on the __import__ function.  Thus,
    // to enable 'import' to function the context of 'exec', the builtins
    // module needs to be within the namespace being used.
    ns["__builtins__"] = python::import(PYTHON_BUILTINS);
    // Execute code.  Modifications to variables will be reflected in
    // the ns.
    python::exec("b = 5", ns);
    std::cout << "b is " << python::extract<int>(ns["b"]) << std::endl;
    // Execute code using the built-in test_module.
    python::exec(
      "import test_modulen"
      "var = test_module.func(b)n",
      ns);
    std::cout << "var is " << python::extract<float>(ns["var"]) << std::endl;
  }
  catch (python::error_already_set&)
  {
    PyErr_Print();
  }
}

执行时,其输出为:

b is 5
var is 24.5