开发者

How to compare python objects which wrap pointers to existing C++ structures?

开发者 https://www.devze.com 2023-03-30 02:26 出处:网络
I have a class method that returns a pointer to an inner data structure (where the data structure is guaranteed to outlive its use in python code). It looks like:

I have a class method that returns a pointer to an inner data structure (where the data structure is guaranteed to outlive its use in python code). It looks like:

class MyClass {
    ...

    some_structure* get() {
        return inner_structure_;
    }

    private:
    some_structure* inner_structure_;
};

I want to wrap this get() method in Boost::Python so that if two different objects of this class return the same pointer, the associated some_structure objects in python compare equal.

Inside the class_<MyClass> definition I've tried wrapping get() with both return_value_policy<reference_existing_object>() and return_inner_reference<>() call policies, but in both cases, calling get() on different python "MyClass" objects returns different some_structure objects even though all point to the same memory address in C++.

How would I get around this? Might there be a hidden property inside the wrapper object that stores the pointer's a开发者_如何学编程ddress, so I can compare those instead?


Figured out a way to do it, although it still feels hackish and that there should be some easier way. But here goes:

1) Define your own methods that compare the pointers.

template <typename T>
bool eq(const T* self, const T* rhs) {                
  return self == rhs;                                                           
}                                                                               

template <typename T>                                                           
bool ne(const T* self, const T* rhs) {                
  return !eq<T>(self, rhs);                                              
}

2) Manually declare the __eq__ and __ne__ inside the wrapper class to point to those methods:

class_<smth>("smth", no_init)
  ...
  .def("__eq__", &eq<smth>)
  .def("__ne__", &ne<smth>);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号