py_ptr.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #pragma once
  2. #include <Python.h> // PyObject
  3. #include <yql/essentials/public/udf/udf_ptr.h>
  4. namespace NPython {
  5. template <typename T>
  6. class TPyPtrOps
  7. {
  8. public:
  9. static inline void Ref(T* t) {
  10. Y_ASSERT(t);
  11. Py_INCREF(t);
  12. }
  13. static inline void UnRef(T* t) {
  14. Y_ASSERT(t);
  15. Py_DECREF(t);
  16. }
  17. static inline ui32 RefCount(const T* t) {
  18. Y_ASSERT(t);
  19. return t->ob_refcnt;
  20. }
  21. };
  22. class TPyObjectPtr:
  23. public NYql::NUdf::TRefCountedPtr<PyObject, TPyPtrOps<PyObject>>
  24. {
  25. using TSelf = NYql::NUdf::TRefCountedPtr<PyObject, TPyPtrOps<PyObject>>;
  26. public:
  27. inline TPyObjectPtr()
  28. {
  29. }
  30. inline TPyObjectPtr(PyObject* p)
  31. : TSelf(p, STEAL_REF) // do not increment refcounter by default
  32. {
  33. }
  34. inline TPyObjectPtr(PyObject* p, AddRef)
  35. : TSelf(p)
  36. {
  37. }
  38. inline void ResetSteal(PyObject* p) {
  39. TSelf::Reset(p, STEAL_REF);
  40. }
  41. inline void ResetAddRef(PyObject* p) {
  42. TSelf::Reset(p);
  43. }
  44. inline void Reset() {
  45. TSelf::Reset();
  46. }
  47. template <class T>
  48. inline T* GetAs() const {
  49. return reinterpret_cast<T*>(Get());
  50. }
  51. void Reset(PyObject* p) = delete;
  52. };
  53. } // namspace NPython