python - 如何将 Boost.Python 中的 map_indexing_suite 与自定义非 std 对象一起使用?

标签 python c++ boost language-interoperability

“map_indexing_suite”用法的简单示例运行良好:

class_<map<int, string> >("testMap")
        .def(map_indexing_suite<std::map<int, string>, true>())
    ;

在 python 方面,它按预期工作:

a = riversim.testMap()
a[1]='sdf'

但是! 如果我尝试在 map 中使用更复杂的对象 BoundaryCondition 而不是 string,例如下一个:

enum t_boundary 
{
    DIRICHLET = 0, 
    NEUMAN
}; 

struct BoundaryCondition
{
    t_boundary type = DIRICHLET;
    double value = 0;

    bool operator==(const BoundaryCondition& bc) const;
    friend ostream& operator <<(ostream& write, const BoundaryCondition & boundary_condition);
};

typedef map<t_boundary_id, BoundaryCondition> t_BoundaryConditions;

BOOST_PYTHON_MODULE(riversim)
{
    enum_<t_boundary>("t_boundary")
        .value("DIRICHLET", DIRICHLET)
        .value("NEUMAN", NEUMAN)
        .export_values()
        ;

    class_<BoundaryCondition>("BoundaryCondition")
        .def_readwrite("value", &BoundaryCondition::value)
        .def_readwrite("type", &BoundaryCondition::type)
        .def(self == self) 
    ;

    //and problematic class:
    class_<River::t_BoundaryConditions >("t_BoundaryConditions")
        .def(map_indexing_suite<t_BoundaryConditions, true>())
    ;

}

它编译得很好,我可以导入riversim:

import riversim

bound = riversim.t_boundary
bc = riversim.BoundaryCondition
bcs = riversim.t_BoundaryConditions

和下一个命令:

bcs[1] = bc

给出错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
----> 1 bcs[1] = bc

TypeError: 'Boost.Python.class' object does not support item assignment

如何正确地将映射移植到Python?

ps:也尝试这个解决方案link它不起作用,出现与上面相同的错误。

最佳答案

首先,

bcs = riversim.t_BoundaryConditions

评估类(class)。必须是

bcs = riversim.t_BoundaryConditions()

现在

bcs[1] = bc

结果

Traceback (most recent call last):
  File "./test.py", line 10, in <module>
    bcs[1] = bc
TypeError: Invalid assignment

这是因为同样的情况也适用于 bc,以下两者都有效:

bcs[1] = bc()
bcs[2] = riversim.BoundaryCondition()

关于python - 如何将 Boost.Python 中的 map_indexing_suite 与自定义非 std 对象一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62323612/

相关文章:

Python - Pip 安装 - 代理错误 - 'Cannot connect to proxy.',OSError'

借用和窃取引用的 Python C-API 函数

c++ - 操作数组

c++ - OpenCV错误: Assertion failed.怎么办?

c++ - 为什么在将 boost::units::make_scaled_unit 与 liter_base_unit 一起使用时会出现编译错误?

python - 防止从 Python 调用 C 类型

c++ - 程序仅在调试器外的 Release模式下崩溃

c++ - bind<void>(ref(acc), _1) 是什么意思?

c++ - 使用函数 <void (boost::any)> 的事件系统是个好主意?

python - 如何在 Python 中打印出字符串 "\b"