aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/udfs/common/python/bindings/py_ptr.h
blob: 704629b86b7bdfd50527c522021fc3754b4f248c (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#pragma once

#include <Python.h> // PyObject

#include <yql/essentials/public/udf/udf_ptr.h>

namespace NPython {

template <typename T>
class TPyPtrOps
{
public:
    static inline void Ref(T* t) {
        Y_ASSERT(t);
        Py_INCREF(t);
    }

    static inline void UnRef(T* t) {
        Y_ASSERT(t);
        Py_DECREF(t);
    }

    static inline ui32 RefCount(const T* t) {
        Y_ASSERT(t);
        return t->ob_refcnt;
    }
};

class TPyObjectPtr:
        public NYql::NUdf::TRefCountedPtr<PyObject, TPyPtrOps<PyObject>>
{
    using TSelf = NYql::NUdf::TRefCountedPtr<PyObject, TPyPtrOps<PyObject>>;

public:
    inline TPyObjectPtr()
    {
    }

    inline TPyObjectPtr(PyObject* p)
        : TSelf(p, STEAL_REF)   // do not increment refcounter by default
    {
    }

    inline TPyObjectPtr(PyObject* p, AddRef)
        : TSelf(p)
    {
    }

    inline void ResetSteal(PyObject* p) {
        TSelf::Reset(p, STEAL_REF);
    }

    inline void ResetAddRef(PyObject* p) {
        TSelf::Reset(p);
    }

    inline void Reset() {
        TSelf::Reset();
    }

    template <class T>
    inline T* GetAs() const {
        return reinterpret_cast<T*>(Get());
    }

    void Reset(PyObject* p) = delete;
};

} // namspace NPython