PythonTypeConversions.hh 15.1 KB
Newer Older
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
/*===========================================================================*\
*                                                                            *
*                              OpenFlipper                                   *
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
*                                                                            *
\*===========================================================================*/

#include <pybind11/include/pybind11/pybind11.h>
#include <pybind11/include/pybind11/numpy.h>

#include <QString>

namespace py = pybind11;

namespace pybind11 { namespace detail {
    template <> struct type_caster<QString> {
    public:
        /**
         * This macro establishes the name 'str' in
         * function signatures and declares a local variable
         * 'value' of type QVariant
         */
        PYBIND11_TYPE_CASTER(QString, _("str"));

        /**
60
         * Conversion part 1 (Python->C++): convert a PyObject into a QString
61
62
63
64
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
        bool load(handle src, bool ) {
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
            /* Extract PyObject from handle */
            PyObject *source = src.ptr();

            if (!PyUnicode_Check(source))
              return false;

            Py_ssize_t size;
            const char *ptr = PyUnicode_AsUTF8AndSize(source, &size);

            if (!ptr) {
                return NULL;
            }

            /* Now try to convert into a C++ int */
            value = QString::fromUtf8(ptr, size);

            /* Ensure return code was OK (to avoid out-of-range errors etc) */
            return ( !PyErr_Occurred() );
        }

        /**
87
         * Conversion part 2 (C++ -> Python): convert an QString instance into
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
        static handle cast(QString src, return_value_policy /* policy */, handle /* parent */) {
            return (PyUnicode_FromString( src.toUtf8().data()) );
        }
    };
}} // namespace pybind11::detail


namespace pybind11 { namespace detail {
    template <> struct type_caster<Vector> {
    public:
        /**
         * This macro establishes the name 'str' in
         * function signatures and declares a local variable
         * 'value' of type QVariant
         */
        PYBIND11_TYPE_CASTER(Vector, _("Vector"));

        /**
111
         * Conversion part 1 (Python->C++): convert a PyObject into a Vector
112
113
114
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
115
        bool load(handle src, bool convert ) {
116
117
118
119

            /* Extract PyObject from handle */
             PyObject* source = src.ptr();

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
             if (  PyList_Check(source) ) {

               if ( PyList_Size(source) != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: List size should be 3!");
                 throw py::error_already_set();
                 return false;
               }

               /* Now try to convert into a C++ int */
               value = Vector(PyFloat_AsDouble(PyList_GetItem(source,0)),PyFloat_AsDouble(PyList_GetItem(source,1)),PyFloat_AsDouble(PyList_GetItem(source,2)));

             } else if ( PyTuple_Check(source) ) {
               if ( PyTuple_Size(source) != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Tuple size should be 3!");
                 throw py::error_already_set();
                 return false;
               }
137

138
139
140
               /* Now try to convert into a C++ int */
               value = Vector(PyFloat_AsDouble(PyTuple_GetItem(source,0)),PyFloat_AsDouble(PyTuple_GetItem(source,1)),PyFloat_AsDouble(PyTuple_GetItem(source,2)));

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
             } else if ( py::cast<py::array>(source) ) {

               py::array array = py::cast<py::array>(source);

               if (  array.size() != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array size should be 3!");
                 throw py::error_already_set();
                 return false;
               }

               if (!convert && !py::array_t<double>::check_(src)) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array, wrong dtype, conversion disabled");
                 return false;
               }

               auto buf = py::array_t<double, py::array::c_style | py::array::forcecast>::ensure(src);

               if (!buf) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array, conversion failed.");
                 return false;
               }
               if (buf.ndim() != 1 || buf.size() != 3) {
                 PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Numpy Array dimension or size error. Dimension should be one, size 3!");
                 return false;
               }

               value = Vector(buf.data());
               return true;

170
             } else {
171
               PyErr_SetString(PyExc_RuntimeError, "Vector Conversion: Not a list or a tuple or a numpy array.");
172
173
174
175
               throw py::error_already_set();
               return false;
             }

176
177
             /* Ensure return code was OK (to avoid out-of-range errors etc) */
             return ( !PyErr_Occurred() );
178
179
180
        }

        /**
181
         * Conversion part 2 (C++ -> Python): convert an Vector instance into
182
183
184
185
186
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
187
188
189
190
        static handle cast(Vector src, return_value_policy /* policy */, handle parent ) {
          // Create numpy array
          py::array a(3, src.data());
          return a.release();
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
        }
    };
}} // namespace pybind11::detail


namespace pybind11 { namespace detail {
    template <> struct type_caster<Matrix4x4> {
    public:
        /**
         * This macro establishes the name 'str' in
         * function signatures and declares a local variable
         * 'value' of type Matrix4x4
         */
        PYBIND11_TYPE_CASTER(Matrix4x4, _("Matrix4x4"));

        /**
         * Conversion part 1 (Python->C++): convert a PyObject into a Matrix4x4
         * instance or return false upon failure. The second argument
         * indicates whether implicit conversions should be applied.
         */
        bool load(handle src, bool convert ) {

            /* Extract PyObject from handle */
             PyObject* source = src.ptr();

             if (  PyList_Check(source) ) {

               if ( PyList_Size(source) != 16) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: List size should be 16!");
                 throw py::error_already_set();
                 return false;
               }

               double convert[16] =  { PyFloat_AsDouble(PyList_GetItem(source,0)),
                                       PyFloat_AsDouble(PyList_GetItem(source,1)),
                                       PyFloat_AsDouble(PyList_GetItem(source,2)),
                                       PyFloat_AsDouble(PyList_GetItem(source,3)),
                                       PyFloat_AsDouble(PyList_GetItem(source,4)),
                                       PyFloat_AsDouble(PyList_GetItem(source,5)),
                                       PyFloat_AsDouble(PyList_GetItem(source,6)),
                                       PyFloat_AsDouble(PyList_GetItem(source,7)),
                                       PyFloat_AsDouble(PyList_GetItem(source,8)),
                                       PyFloat_AsDouble(PyList_GetItem(source,9)),
                                       PyFloat_AsDouble(PyList_GetItem(source,0)),
                                       PyFloat_AsDouble(PyList_GetItem(source,11)),
                                       PyFloat_AsDouble(PyList_GetItem(source,12)),
                                       PyFloat_AsDouble(PyList_GetItem(source,13)),
                                       PyFloat_AsDouble(PyList_GetItem(source,14))};

               /* Now convert into a C++ Matrix4x4 */
               value = Matrix4x4(convert);

             } else if ( PyTuple_Check(source) ) {
               if ( PyTuple_Size(source) != 16) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Tuple size should be 3!");
                 throw py::error_already_set();
                 return false;
               }

               double convert[16] =  { PyFloat_AsDouble(PyTuple_GetItem(source,0)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,1)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,2)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,3)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,4)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,5)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,6)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,7)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,8)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,9)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,0)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,11)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,12)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,13)),
                                       PyFloat_AsDouble(PyTuple_GetItem(source,14)) };

               /* Now convert into a C++ Matrix4x4 */
               value = Matrix4x4(convert);

             } else if ( py::cast<py::array>(source) ) {

               py::array array = py::cast<py::array>(source);

               if (  array.size() != 16) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array size should be 16!");
                 throw py::error_already_set();
                 return false;
               }
278

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
               if (!convert && !py::array_t<double>::check_(src)) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array, wrong dtype, conversion disabled");
                 return false;
               }

               auto buf = py::array_t<double, py::array::c_style | py::array::forcecast>::ensure(src);

               if (!buf) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array, conversion failed.");
                 return false;
               }

               // Check Dimension   : Matrix has 2 dimensions
               // Check buffer size : 4x4 -> 16 entries
               // Check shape       : 2 dimensions, each has size 4
               if (buf.ndim() != 2 || buf.size() != 16 || buf.shape()[0] !=4  || buf.shape()[1] !=4) {
                 PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Numpy Array dimension or size error. Dimension should be four, size 16, and shape 4x4!");
                 return false;
               }

               value = Matrix4x4(buf.data());
               return true;

             } else {
               PyErr_SetString(PyExc_RuntimeError, "Matrix4x4 Conversion: Not a list or a tuple or a numpy array.");
               throw py::error_already_set();
               return false;
             }

             /* Ensure return code was OK (to avoid out-of-range errors etc) */
             return ( !PyErr_Occurred() );
        }

        /**
         * Conversion part 2 (C++ -> Python): convert an Matrix4x4 instance into
         * a Python object. The second and third arguments are used to
         * indicate the return value policy and parent object (for
         * ``return_value_policy::reference_internal``) and are generally
         * ignored by implicit casters.
         */
        static handle cast(Matrix4x4 src, return_value_policy /* policy */, handle parent ) {
          // Create numpy array
          py::array a({4,4}, src.data());
          return a.release();
323
324
325
        }
    };
}} // namespace pybind11::detail