使用 Boost.Python 从 X 导入 Y

from X import Y with Boost.Python

我想从另一个文件夹导入 class。在另一个 python 脚本中我会做

from Base.Derived import Class

但是我不知道如何用 Boost.Python 做到这一点。该库提供了 import.hpp 可以让你做这样的事情

object module = import("Base.Derived");

但是 python 中的等价物是

import Base.Derived

最终目标是将实例化的 python 对象转换为 Base 指针,因此最好使用 Boost.Python。理想情况下,代码看起来像这样

object module = some form of "from Base.Derived import Class"

// Get a C++ pointer of the derived python class.
object derived = module.attr("Class")();
Card* card = extract< Card* >(derived);

"dotted" 表示法中的每个名称都是其父项的属性。你的最后一段代码几乎是正确的(尽管我怀疑名字有些混淆):

boost::python::object Class = boost::python::import("Base.Derived").attr("Class");
boost::python::object class_instance = Class();