【问题标题】:Boost python, compare raw pointer to managed pointer?Boost python,将原始指针与托管指针进行比较?
【发布时间】:2012-05-16 04:52:24
【问题描述】:

所以我有一个std::map<KeyType, std::shared_ptr<ValueType>> 使用map_indexing_suite 暴露给python。

在代码的其他地方,我使用原始指针ValueType* 将对ValueType 对象的引用存储在映射中,因为这些容器不拥有ValueType 对象,而映射拥有。

我的问题是,如何将原始指针公开给 python,使其可以将该引用与共享指针进行比较?像这样的:

valueRef = getRawReference()
for x in myMap:
    if x.data() == valueRef:
        print "match"

【问题讨论】:

  • 在 C++ 中,它将是 &** 将共享指针转换为对其指向的对象的引用。 & 将引用转换为它所引用的对象的地址。

标签: c++ python boost


【解决方案1】:

自己找到了答案。

先定义两个方法:

bool eq(std::shared_ptr<ValueType> lhs, ValueType* rhs)
{
    return lhs.get() == rhs;
}

bool neq(std::shared_ptr<ValueType> lhs, ValueType* rhs)
{
    return lhs.get() != rhs;
}

然后在您的 BOOST_PYTHON_MODULE 中:

bp::def("getRawReference", getRawReference, bp::return_value_policy<bp::reference_existing_object>())

bp::class_<ValueType, std::shared_ptr<ValueType>>("ValueType")
    .def("__eq__", eq)
    .def("__neq__", neq);

【讨论】:

  • __neq__ 应该是__ne__
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 2013-04-25
相关资源
最近更新 更多