aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/pybind/ptr.h
blob: e136736690423326f7844dc974373a3fa302deee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#pragma once

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <util/generic/ptr.h>

namespace NPyBind {
    template <class T>
    class TPythonIntrusivePtrOps {
    public:
        static inline void Ref(T* t) noexcept {
            Py_XINCREF(t);
        }

        static inline void UnRef(T* t) noexcept {
            Py_XDECREF(t);
        }

        static inline void DecRef(T* t) noexcept {
            Py_XDECREF(t);
        }
    };

    class TPyObjectPtr: public TIntrusivePtr<PyObject, TPythonIntrusivePtrOps<PyObject>> {
    private:
        typedef TIntrusivePtr<PyObject, TPythonIntrusivePtrOps<PyObject>> TParent;
        typedef TPythonIntrusivePtrOps<PyObject> TOps;

    public:
        inline TPyObjectPtr() noexcept {
        }

        inline explicit TPyObjectPtr(PyObject* obj) noexcept
            : TParent(obj)
        {
        }

        inline TPyObjectPtr(PyObject* obj, bool unref) noexcept
            : TParent(obj)
        {
            if (unref)
                TOps::UnRef(TParent::Get());
        }

        inline PyObject* RefGet() {
            TOps::Ref(TParent::Get());
            return TParent::Get();
        }
    };

}