gpt4 book ai didi

c++ - Boost::Python:嵌入和加载 Boost::Python 模块和转换器

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:19 28 4
gpt4 key购买 nike

这可能是一个微不足道的问题,但我有点被困在这里。

我有以下设置:

  • entity.cpp/.hpp:包含我的实体类定义和实现。
  • entity_wrap.cpp:我编译成 entity.so
  • 的 boost python 包装文件
  • 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 本身。

关于c++ - Boost::Python:嵌入和加载 Boost::Python 模块和转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7978951/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com