Boost::Python:嵌入并加载Boost::Python模块和转换器

Boost::Python: embed and load Boost::Python modules and converters

本文关键字:Boost Python 模块 转换器 加载      更新时间:2023-10-16

这可能是一个微不足道的问题,但我有点拘泥于此。

我有以下设置:

  • entity.cpp/.hpp:包含我的Entity类定义和实现
  • entity_wrap.cpp:我的boost python包装文件,我将其编译为entity.so
  • entity_test.cpp:测试文件

我想在entity_test.cpp中做以下操作:

Py_SetProgramName(argv[0]);
Py_Initialize();
...
Entity* entity = new Entity;
globals["entity"] = entity;

我现在得到以下异常:

TypeError: No to_python (by-value) converter found for C++ type: Entity

这是显而易见的,因为我没有加载类型的转换定义。我现在尝试用globals["entity_module"] = import("entity");加载entity.so,但遇到了这个异常:

ImportError: No module named entity

我可以按预期从python shell加载模块。

我现在的问题是:如何加载entity_wrap.cpp中定义的转换器?


解决方案

正如eudoxos所述,我必须确保我要加载的模块在sys.path:中

globals["sys"] = import("sys");
exec("sys.path.append('/path/to/my/module')n"
     "import entity", globals);

它现在就像一个符咒。显然,仅仅使用Py_SetProgramName(argv[0]);是不够的。

使用boost::python::import;注意sys.path,以便找到您的模块,您可能需要添加对的调用

PyRun_SimpleString("import sys; sys.path.append('.');")

首先。好吧,你也可以通过PyRun_SimpleString进行导入,然后:-(

另一种选择是:用python编写entity_test本身。