ptr.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #pragma once
  2. #define PY_SSIZE_T_CLEAN
  3. #include <Python.h>
  4. #include <util/generic/ptr.h>
  5. namespace NPyBind {
  6. template <class T>
  7. class TPythonIntrusivePtrOps {
  8. public:
  9. static inline void Ref(T* t) noexcept {
  10. Py_XINCREF(t);
  11. }
  12. static inline void UnRef(T* t) noexcept {
  13. Py_XDECREF(t);
  14. }
  15. static inline void DecRef(T* t) noexcept {
  16. Py_XDECREF(t);
  17. }
  18. };
  19. class TPyObjectPtr: public TIntrusivePtr<PyObject, TPythonIntrusivePtrOps<PyObject>> {
  20. private:
  21. typedef TIntrusivePtr<PyObject, TPythonIntrusivePtrOps<PyObject>> TParent;
  22. typedef TPythonIntrusivePtrOps<PyObject> TOps;
  23. public:
  24. inline TPyObjectPtr() noexcept {
  25. }
  26. inline explicit TPyObjectPtr(PyObject* obj) noexcept
  27. : TParent(obj)
  28. {
  29. }
  30. inline TPyObjectPtr(PyObject* obj, bool unref) noexcept
  31. : TParent(obj)
  32. {
  33. if (unref)
  34. TOps::UnRef(TParent::Get());
  35. }
  36. inline PyObject* RefGet() {
  37. TOps::Ref(TParent::Get());
  38. return TParent::Get();
  39. }
  40. };
  41. }