File: pyutils.h

package info (click to toggle)
pytango 10.1.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,304 kB
  • sloc: python: 27,795; cpp: 16,150; sql: 252; sh: 152; makefile: 43
file content (204 lines) | stat: -rw-r--r-- 7,232 bytes parent folder | download
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
 * SPDX-FileCopyrightText: All Contributors to the PyTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#pragma once

#include <omnithread.h>
#include <bytesobject.h>
#include "common_header.h"
#include "types_structs_macros.h"

inline py::dict create_dict_from_lists(py::list keys, py::list values) {
    // Check that both lists have the same length
    if(keys.size() != values.size()) {
        throw std::runtime_error("Keys and values must have the same length");
    }

    py::dict dict;
    for(std::size_t i = 0; i < keys.size(); ++i) {
        dict[keys[i]] = values[i];
    }

    return dict;
}

inline py::dict create_dict_from_list(py::list values) {
    py::dict dict;
    for(std::size_t i = 0; i < values.size(); ++i) {
        dict[py::int_(values[i])] = values[i];
    }

    return dict;
}

inline void add_names_values_to_native_enum(py::object enum_class) {
    py::dict members = enum_class.attr("__members__");
    py::list keys = members.attr("keys")();
    py::list values = members.attr("values")();
    enum_class.attr("values") = create_dict_from_list(values);
    enum_class.attr("names") = create_dict_from_lists(keys, values);

    enum_class.attr("__str__") = py::cpp_function(
        [](py::object self) {
            return self.attr("name");
        },
        py::is_method(enum_class) // Tell pybind11 this will be a method
    );
}

/// This callback is run to delete Tango::DevVarXArray* objects.
/// It is called by python. The array was associated with an attribute
/// value object that is not being used anymore.
template <int tangoTypeConst>
void dev_var_attribute_array_deleter(void *ptr) {
    delete static_cast<typename TANGO_const2arraytype(tangoTypeConst) *>(ptr);
}

template <typename TangoArrayType>
void dev_var_command_array_deleter(void *ptr) {
    delete static_cast<TangoArrayType *>(ptr);
}

/// Workaround for https://github.com/pybind/pybind11/issues/5998:
/// pybind11_object_dealloc() does not call PyObject_ClearManagedDict() before tp_free()
/// on Python 3.13+, so objects stored in the __dict__ of py::dynamic_attr() instances
/// have their refcounts permanently abandoned when the pybind11 object is freed.
/// Call this after defining any py::class_<T> with py::dynamic_attr().
/// Can be removed once a fixed pybind11 release is used.
///
/// Templatized so that each instantiation has its own `orig` static, ensuring
/// correctness if different types ever have different tp_dealloc implementations.
/// The captureless lambda can reference `orig` without capturing because static
/// local variables have fixed storage and require no closure.
template <typename T>
inline void fix_dynamic_attr_dealloc() {
#if PY_VERSION_HEX >= 0x030D0000
    static destructor orig = nullptr;
    auto *type = reinterpret_cast<PyTypeObject *>(py::type::of<T>().ptr());
    if(!PyType_HasFeature(type, Py_TPFLAGS_MANAGED_DICT)) {
        return;
    }
    if(orig == nullptr) {
        orig = type->tp_dealloc;
    }
    type->tp_dealloc = [](PyObject *self) noexcept {
        PyObject_ClearManagedDict(self);
        orig(self);
    };
#endif
}

inline void raise_(PyObject *type, const char *message) {
    PyErr_SetString(type, message);
    throw py::error_already_set();
}

inline PyObject *EncodeAsLatin1(PyObject *in) {
    PyObject *bytes_out = PyUnicode_AsLatin1String(in);
    if(bytes_out == nullptr) {
        PyObject *bytes_replaced = PyUnicode_AsEncodedString(in, "latin-1", "replace");
        const char *string_replaced = PyBytes_AsString(bytes_replaced);
        std::string err_msg = "Can't encode ";
        if(string_replaced == nullptr) {
            err_msg += "unknown Unicode string as Latin-1";
        } else {
            err_msg += "'";
            err_msg += string_replaced;
            err_msg += "' Unicode string as Latin-1 (bad chars replaced with ?)";
        }
        Py_XDECREF(bytes_replaced);
        raise_(PyExc_UnicodeError, err_msg.c_str());
    }

    return bytes_out;
}

inline PyObject *PyObject_GetAttrString_(PyObject *o, const std::string &attr_name) {
    const char *attr = attr_name.c_str();
    return PyObject_GetAttrString(o, attr);
}

inline PyObject *PyImport_ImportModule_(const std::string &name) {
    const char *attr = name.c_str();
    return PyImport_ImportModule(attr);
}

py::object from_cpp_str_to_pybind11_str(const std::string &in,
                                        const char *encoding = nullptr, /* defaults to latin-1 */
                                        const char *errors = "strict");

py::object from_cpp_char_to_pybind11_str(const char *in,
                                         Py_ssize_t size = -1,
                                         const char *encoding = nullptr, /* defaults to latin-1 */
                                         const char *errors = "strict");

char *from_python_str_to_cpp_char(PyObject *obj_ptr,
                                  Py_ssize_t *size_out = nullptr,
                                  bool utf_encoding = false /* defaults to latin-1 */);

char *from_python_str_to_cpp_char(const py::object &in,
                                  Py_ssize_t *size_out = nullptr,
                                  bool utf_encoding = false /* defaults to latin-1 */);

void throw_bad_type(const char *type, const char *source);

void view_pybytes_as_char_array(const py::object &py_value, Tango::DevVarCharArray &out_array);

// Delete a pointer for a CppTango class with Python GIL released.
// Typically used by shared_ptr constructors as the function
// to call when the object is deleted.
struct DeleterWithoutGIL {
    template <typename T>
    void operator()(T *ptr) const {
        py::gil_scoped_release no_gil;
        delete ptr;
    }
};

/**
 * Determines if the given method name exists and is callable
 * within the python class
 *
 * @param[in] obj object to search for the method
 * @param[in] method_name the name of the method
 *
 * @return returns true is the method exists or false otherwise
 */
bool is_method_defined(py::object &obj, const std::string &method_name);

/**
 * Determines if the given method name exists and is callable
 * within the python class
 *
 * @param[in] obj object to search for the method
 * @param[in] method_name the name of the method
 * @param[out] exists set to true if the symbol exists or false otherwise
 * @param[out] is_method set to true if the symbol exists and is a method
 *             or false otherwise
 */
void is_method_defined(py::object &obj, const std::string &method_name, bool &exists, bool &is_method);

inline py::list pickle_stdstringvector(const StdStringVector &vector) {
    // Convert extensions to a Python list of strings
    py::list list;
    for(const auto &v : vector) {
        list.append(v);
    }
    return list;
}

inline StdStringVector unpickled_stdstringvector(py::list py_value) {
    // Convert the Python list back to StdStringVector
    StdStringVector vector;
    for(auto item : py_value) {
        vector.push_back(item.cast<std::string>());
    }
    return vector;
}

#define PYTANGO_MOD py::object pytango(py::module_::import("tango"));

#define CALL_METHOD(retType, self, name, ...) elf.attr(name)(__VA_ARGS__).cast<retType>();