File indexing completed on 2024-04-14 04:35:54

0001 /*
0002     SPDX-FileCopyrightText: 2020 David Faure <faure@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 #include <boost/python/converter/registry.hpp>
0007 #include <boost/python/to_python_converter.hpp>
0008 #include <boost/python/object.hpp>
0009 #include <QByteArray>
0010 
0011 using namespace boost::python;
0012 
0013 struct QByteArray_to_python_str
0014 {
0015   static PyObject* convert(QByteArray const& s)
0016   {
0017       return incref(object(s.constData()).ptr());
0018   }
0019 };
0020 
0021 struct QByteArray_from_python_str
0022 {
0023     QByteArray_from_python_str()
0024     {
0025         converter::registry::push_back(&convertible, &construct, type_id<QByteArray>());
0026     }
0027 
0028     // Determine if objPtr can be converted in a QByteArray
0029     static void* convertible(PyObject* obj_ptr)
0030     {
0031         if (!PyUnicode_Check(obj_ptr)) return nullptr;
0032         return obj_ptr;
0033     }
0034 
0035     // Convert objPtr into a QByteArray
0036     static void construct(PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data)
0037     {
0038         // Extract the character data from the python string
0039         handle<> rawBytesHandle{PyUnicode_AsUTF8String(obj_ptr)};
0040         Q_ASSERT(rawBytesHandle);
0041 
0042         // Grab pointer to memory into which to construct the new QByteArray
0043         void* storage = ((converter::rvalue_from_python_storage<QByteArray>*) data)->storage.bytes;
0044 
0045         // in-place construct the new QByteArray using the character data extracted from the python object
0046         new (storage) QByteArray{PyBytes_AsString(rawBytesHandle.get()), int(PyBytes_Size(rawBytesHandle.get()))};
0047         data->convertible = storage;
0048     }
0049 };
0050 
0051 void register_qt_wrappers()
0052 {
0053     to_python_converter<
0054             QByteArray,
0055             QByteArray_to_python_str>();
0056     QByteArray_from_python_str();
0057 }