Boost python, compare raw pointer to managed point

2019-08-12 04:32发布

问题:

So I have an std::map<KeyType, std::shared_ptr<ValueType>> exposed up to python using map_indexing_suite.

In other places in the code I store references to the ValueType objects in the map using raw pointers, ValueType*, because those containers don't own the ValueType objects, the map does.

My question is, how can I expose the raw pointer to python in a way it can compare that reference to the shared pointer? Something like this:

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

回答1:

Found the answer myself.

First define two methods:

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;
}

Then in your 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);


标签: c++ python boost