Project

General

Profile

Known Issues » test.cpp

jun chen, 03/09/2025 11:59 PM

 
// #include <bits/stdc++.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>

struct MyId {
MyId(int iid) : iid_(iid) {}
int iid_;
MyId &operator=(const MyId &id) {
if (this == &id)
return *this;
this->iid_ = id.iid_;
return *this;
};
int getid() { return iid_; }
};

// define custom operator functions,otherwise the compilation will fail in this
// case
bool operator==(const MyId &myid1, const MyId &myid2) {
return myid1.iid_ == myid2.iid_;
};

namespace std {
template <> class hash<MyId> {
public:
size_t operator()(const MyId &myid) const { return myid.iid_; };
};
}; // namespace std

using MyMap = std::unordered_map<MyId, int>;

namespace py = pybind11;

PYBIND11_MAKE_OPAQUE(MyMap);

PYBIND11_MODULE(test, m) {
// export customer class
py::class_<MyId>(m, "MyId").def(py::init<int>()).def("getid", &MyId::getid);
py::bind_map<MyMap>(m, "MyMap");
// do implicit convert
py::implicitly_convertible<int, MyId>();
}
(4-4/4)