pygi-marshal-from-py.c 62.2 KB
Newer Older
1
2
3
/* -*- Mode: C; c-basic-offset: 4 -*-
 * vim: tabstop=4 shiftwidth=4 expandtab
 *
4
 * Copyright (C) 2011 John (J5) Palmieri <johnp@redhat.com>,  Red Hat, Inc.
5
 *
6
 *   pygi-marshal-from-py.c: Functions to convert PyObjects to C types.
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
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
 * USA
 */

#include "pygi-private.h"

#include <string.h>
#include <time.h>
#include <pygobject.h>
#include <pyglib-python-compat.h>

#include "pygi-cache.h"
32
#include "pygi-marshal-cleanup.h"
33
#include "pygi-marshal-from-py.h"
34

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#ifdef _WIN32
#ifdef _MSC_VER
#include <math.h>

#ifndef NAN
static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
#define NAN (*(const float *) __nan)
#endif

#ifndef INFINITY
#define INFINITY HUGE_VAL
#endif

#endif
#endif

51
static gboolean
David Malcolm's avatar
David Malcolm committed
52
53
54
55
56
57
58
gi_argument_from_py_ssize_t (GIArgument   *arg_out,
                             Py_ssize_t    size_in,
                             GITypeTag     type_tag)                             
{
    switch (type_tag) {
    case GI_TYPE_TAG_VOID:
    case GI_TYPE_TAG_BOOLEAN:
59
60
        goto unhandled_type;

David Malcolm's avatar
David Malcolm committed
61
    case GI_TYPE_TAG_INT8:
62
63
64
65
66
67
68
        if (size_in >= G_MININT8 && size_in <= G_MAXINT8) {
            arg_out->v_int8 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
69
    case GI_TYPE_TAG_UINT8:
70
71
72
73
74
75
76
        if (size_in >= 0 && size_in <= G_MAXUINT8) {
            arg_out->v_uint8 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
77
    case GI_TYPE_TAG_INT16:
78
79
80
81
82
83
84
        if (size_in >= G_MININT16 && size_in <= G_MAXINT16) {
            arg_out->v_int16 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
85
    case GI_TYPE_TAG_UINT16:
86
87
88
89
90
91
        if (size_in >= 0 && size_in <= G_MAXUINT16) {
            arg_out->v_uint16 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }
David Malcolm's avatar
David Malcolm committed
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

        /* Ranges assume two's complement */
    case GI_TYPE_TAG_INT32:
        if (size_in >= G_MININT32 && size_in <= G_MAXINT32) {
            arg_out->v_int32 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

    case GI_TYPE_TAG_UINT32:
        if (size_in >= 0 && size_in <= G_MAXUINT32) {
            arg_out->v_uint32 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

    case GI_TYPE_TAG_INT64:
        arg_out->v_int64 = size_in;
        return TRUE;

    case GI_TYPE_TAG_UINT64:
        if (size_in >= 0) {
            arg_out->v_uint64 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }
            
    case GI_TYPE_TAG_FLOAT:
    case GI_TYPE_TAG_DOUBLE:
    case GI_TYPE_TAG_GTYPE:
    case GI_TYPE_TAG_UTF8:
    case GI_TYPE_TAG_FILENAME:
    case GI_TYPE_TAG_ARRAY:
    case GI_TYPE_TAG_INTERFACE:
    case GI_TYPE_TAG_GLIST:
    case GI_TYPE_TAG_GSLIST:
    case GI_TYPE_TAG_GHASH:
    case GI_TYPE_TAG_ERROR:
    case GI_TYPE_TAG_UNICHAR:
    default:
        goto unhandled_type;
    }

 overflow:
    PyErr_Format (PyExc_OverflowError,
                  "Unable to marshal C Py_ssize_t %zd to %s",
                  size_in,
                  g_type_tag_to_string (type_tag));
    return FALSE;

 unhandled_type:
    PyErr_Format (PyExc_TypeError,
                  "Unable to marshal C Py_ssize_t %zd to %s",
                  size_in,
                  g_type_tag_to_string (type_tag));
    return FALSE;
}

153
static gboolean
David Malcolm's avatar
David Malcolm committed
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
gi_argument_from_c_long (GIArgument *arg_out,
                         long        c_long_in,
                         GITypeTag   type_tag)
{
    switch (type_tag) {
      case GI_TYPE_TAG_INT8:
          arg_out->v_int8 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT8:
          arg_out->v_uint8 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT16:
          arg_out->v_int16 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT16:
          arg_out->v_uint16 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT32:
          arg_out->v_int32 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT32:
          arg_out->v_uint32 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT64:
          arg_out->v_int64 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT64:
          arg_out->v_uint64 = c_long_in;
          return TRUE;
      default:
          PyErr_Format (PyExc_TypeError,
                        "Unable to marshal C long %ld to %s",
                        c_long_in,
                        g_type_tag_to_string (type_tag));
          return FALSE;
    }
}

192
193
194
195
196
/*
 * _is_union_member - check to see if the py_arg is actually a member of the
 * expected C union
 */
static gboolean
197
_is_union_member (GIInterfaceInfo *interface_info, PyObject *py_arg) {
198
199
200
201
202
203
    gint i;
    gint n_fields;
    GIUnionInfo *union_info;
    GIInfoType info_type;
    gboolean is_member = FALSE;

204
    info_type = g_base_info_get_type (interface_info);
205
206
207
208

    if (info_type != GI_INFO_TYPE_UNION)
        return FALSE;

209
    union_info = (GIUnionInfo *) interface_info;
210
211
212
213
214
215
216
217
218
219
220
    n_fields = g_union_info_get_n_fields (union_info);

    for (i = 0; i < n_fields; i++) {
        GIFieldInfo *field_info;
        GITypeInfo *field_type_info;

        field_info = g_union_info_get_field (union_info, i);
        field_type_info = g_field_info_get_type (field_info);

        /* we can only check if the members are interfaces */
        if (g_type_info_get_tag (field_type_info) == GI_TYPE_TAG_INTERFACE) {
221
            GIInterfaceInfo *field_iface_info;
222
223
            PyObject *py_type;

224
225
            field_iface_info = g_type_info_get_interface (field_type_info);
            py_type = _pygi_type_import_by_gi_info ((GIBaseInfo *) field_iface_info);
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

            if (py_type != NULL && PyObject_IsInstance (py_arg, py_type)) {
                is_member = TRUE;
            }

            Py_XDECREF (py_type);
            g_base_info_unref ( ( GIBaseInfo *) field_iface_info);
        }

        g_base_info_unref ( ( GIBaseInfo *) field_type_info);
        g_base_info_unref ( ( GIBaseInfo *) field_info);

        if (is_member)
            break;
    }

    return is_member;
}

245
gboolean
246
247
248
249
250
_pygi_marshal_from_py_void (PyGIInvokeState   *state,
                            PyGICallableCache *callable_cache,
                            PyGIArgCache      *arg_cache,
                            PyObject          *py_arg,
                            GIArgument        *arg)
251
252
253
{
    g_warn_if_fail (arg_cache->transfer == GI_TRANSFER_NOTHING);

254
255
256
    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
    } else if (PYGLIB_CPointer_Check(py_arg)) {
257
258
        arg->v_pointer = PYGLIB_CPointer_GetPointer (py_arg, NULL);
    } else {
259
260
261
262
263
264
265
266
267
268
269
270
271
        /* NOTE: This will change to only allow integers and the deprecation
         * warning will become a runtime exception. Using the following:
         * arg->v_pointer = PyLong_AsVoidPtr (py_arg);
         * See: https://bugzilla.gnome.org/show_bug.cgi?id=688081
         */

        if (!PYGLIB_PyLong_Check(py_arg) && !PyLong_Check(py_arg)) {
            if (PyErr_WarnEx(PyGIDeprecationWarning,
                             "Pointer arguments will be restricted to integers, capsules, and None. "
                             "See: https://bugzilla.gnome.org/show_bug.cgi?id=683599",
                             1))
                return FALSE;
        }
272
273
        arg->v_pointer = py_arg;
    }
274
275
276
277

    return TRUE;
}

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
static gboolean
check_valid_double (double x, double min, double max)
{
    char buf[100];

    if ((x < min || x > max) && x != INFINITY && x != -INFINITY && x != NAN) {
        if (PyErr_Occurred())
            PyErr_Clear ();

        /* we need this as PyErr_Format() does not support float types */
        snprintf (buf, sizeof (buf), "%g not in range %g to %g", x, min, max);
        PyErr_SetString (PyExc_ValueError, buf);
        return FALSE;
    }
    return TRUE;
}

295
296
static gboolean
_pygi_py_arg_to_double (PyObject *py_arg, double *double_)
297
298
299
{
    PyObject *py_float;

300
    if (!PyNumber_Check (py_arg)) {
301
302
303
304
305
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

306
    py_float = PyNumber_Float (py_arg);
307
308
309
    if (!py_float)
        return FALSE;

310
    *double_ = PyFloat_AsDouble (py_float);
311
    Py_DECREF (py_float);
312

313
314
315
316

    return TRUE;
}

317
318
static gboolean
_pygi_marshal_from_py_float (PyObject          *py_arg,
319
320
321
322
323
324
325
                             GIArgument        *arg)
{
    double double_;

    if (!_pygi_py_arg_to_double (py_arg, &double_))
        return FALSE;

326
    if (PyErr_Occurred () || !check_valid_double (double_, -G_MAXFLOAT, G_MAXFLOAT))
327
328
329
330
331
332
        return FALSE;

    arg->v_float = double_;
    return TRUE;
}

333
334
static gboolean
_pygi_marshal_from_py_double (PyObject          *py_arg,
335
                              GIArgument        *arg)
336
337
338
{
    double double_;

339
    if (!_pygi_py_arg_to_double (py_arg, &double_))
340
341
        return FALSE;

342
    if (PyErr_Occurred () || !check_valid_double (double_, -G_MAXDOUBLE, G_MAXDOUBLE))
343
344
345
346
347
348
        return FALSE;

    arg->v_double = double_;
    return TRUE;
}

349
350
static gboolean
_pygi_marshal_from_py_unichar (PyObject          *py_arg,
351
                               GIArgument        *arg)
352
353
354
355
{
    Py_ssize_t size;
    gchar *string_;

356
357
358
359
360
    if (py_arg == Py_None) {
        arg->v_uint32 = 0;
        return FALSE;
    }

361
362
363
364
    if (PyUnicode_Check (py_arg)) {
       PyObject *py_bytes;

       size = PyUnicode_GET_SIZE (py_arg);
365
       py_bytes = PyUnicode_AsUTF8String (py_arg);
366
367
368
       if (!py_bytes)
           return FALSE;

Martin Pitt's avatar
Martin Pitt committed
369
       string_ = g_strdup(PYGLIB_PyBytes_AsString (py_bytes));
370
       Py_DECREF (py_bytes);
371
372
373
374
375
376
377
378

#if PY_VERSION_HEX < 0x03000000
    } else if (PyString_Check (py_arg)) {
       PyObject *pyuni = PyUnicode_FromEncodedObject (py_arg, "UTF-8", "strict");
       if (!pyuni)
           return FALSE;

       size = PyUnicode_GET_SIZE (pyuni);
379
380
       string_ = g_strdup (PyString_AsString(py_arg));
       Py_DECREF (pyuni);
381
382
383
384
385
386
387
388
#endif
    } else {
       PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                     py_arg->ob_type->tp_name);
       return FALSE;
    }

    if (size != 1) {
389
390
       PyErr_Format (PyExc_TypeError, "Must be a one character string, not %lld characters",
                     (long long) size);
391
       g_free (string_);
392
393
394
       return FALSE;
    }

395
396
    arg->v_uint32 = g_utf8_get_char (string_);
    g_free (string_);
397
398
399

    return TRUE;
}
400

401
402
static gboolean
_pygi_marshal_from_py_gtype (PyObject          *py_arg,
403
                             GIArgument        *arg)
404
405
406
407
408
409
410
411
412
413
414
415
{
    long type_ = pyg_type_from_object (py_arg);

    if (type_ == 0) {
        PyErr_Format (PyExc_TypeError, "Must be gobject.GType, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    arg->v_long = type_;
    return TRUE;
}
416
417
418

static gboolean
_pygi_marshal_from_py_utf8 (PyObject          *py_arg,
419
                            GIArgument        *arg)
420
421
422
423
424
425
426
427
{
    gchar *string_;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

428
    if (PyUnicode_Check (py_arg)) {
429
430
431
432
        PyObject *pystr_obj = PyUnicode_AsUTF8String (py_arg);
        if (!pystr_obj)
            return FALSE;

433
434
        string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj));
        Py_DECREF (pystr_obj);
435
436
    }
#if PY_VERSION_HEX < 0x03000000
437
438
    else if (PyString_Check (py_arg)) {
        string_ = g_strdup (PyString_AsString (py_arg));
439
440
441
442
443
444
445
446
447
448
449
450
    }
#endif
    else {
        PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    arg->v_string = string_;
    return TRUE;
}

451
452
static gboolean
_pygi_marshal_from_py_filename (PyObject          *py_arg,
453
                                GIArgument        *arg)
454
455
456
457
{
    gchar *string_;
    GError *error = NULL;

458
    if (PyUnicode_Check (py_arg)) {
459
460
461
462
        PyObject *pystr_obj = PyUnicode_AsUTF8String (py_arg);
        if (!pystr_obj)
            return FALSE;

463
464
        string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj));
        Py_DECREF (pystr_obj);
465
466
    }
#if PY_VERSION_HEX < 0x03000000
467
468
    else if (PyString_Check (py_arg)) {
        string_ = g_strdup (PyString_AsString (py_arg));
469
470
471
472
473
474
475
476
477
    }
#endif
    else {
        PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    arg->v_string = g_filename_from_utf8 (string_, -1, NULL, NULL, &error);
478
    g_free (string_);
479
480
481

    if (arg->v_string == NULL) {
        PyErr_SetString (PyExc_Exception, error->message);
482
        g_error_free (error);
483
484
485
486
487
488
489
        /* TODO: Convert the error to an exception. */
        return FALSE;
    }

    return TRUE;
}

490
491
492
493
494
495
496
497
static gboolean
_pygi_marshal_from_py_long (PyObject   *object,   /* in */
                            GIArgument *arg,      /* out */
                            GITypeTag   type_tag,
                            GITransfer  transfer)
{
    PyObject *number;

498
499
500
501
502
503
    if (!PyNumber_Check (object)) {
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      object->ob_type->tp_name);
        return FALSE;
    }

504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#if PY_MAJOR_VERSION < 3
    {
        PyObject *tmp = PyNumber_Int (object);
        if (tmp) {
            number = PyNumber_Long (tmp);
            Py_DECREF (tmp);
        } else {
            number = PyNumber_Long (object);
        }
    }
#else
    number = PyNumber_Long (object);
#endif

    if (number == NULL) {
        PyErr_SetString (PyExc_TypeError, "expected int argument");
        return FALSE;
    }

    switch (type_tag) {
        case GI_TYPE_TAG_INT8:
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
        {
            long long_value = PyLong_AsLong (number);
            if (long_value < G_MININT8 || long_value > G_MAXINT8) {
                PyErr_Format (PyExc_ValueError, "%ld not in range %ld to %ld",
                              long_value, (long)G_MININT8, (long)G_MAXINT8);
            } else {
                arg->v_int8 = long_value;
            }
            break;
        }

        case GI_TYPE_TAG_UINT8:
        {
            long long_value = PyLong_AsLong (number);
            if (long_value < 0 || long_value > G_MAXUINT8) {
                PyErr_Format (PyExc_ValueError, "%ld not in range %ld to %ld",
                              long_value, (long)0, (long)G_MAXUINT8);
            } else {
                arg->v_uint8 = long_value;
            }
545
            break;
546
        }
547
548

        case GI_TYPE_TAG_INT16:
549
550
551
552
553
554
555
556
        {
            long long_value = PyLong_AsLong (number);
            if (long_value < G_MININT16 || long_value > G_MAXINT16) {
                PyErr_Format (PyExc_ValueError, "%ld not in range %ld to %ld",
                              long_value, (long)G_MININT16, (long)G_MAXINT16);
            } else {
                arg->v_int16 = long_value;
            }
557
            break;
558
        }
559

560
561
562
563
564
565
566
567
568
        case GI_TYPE_TAG_UINT16:
        {
            long long_value = PyLong_AsLong (number);
            if (long_value < 0 || long_value > G_MAXUINT16) {
                PyErr_Format (PyExc_ValueError, "%ld not in range %ld to %ld",
                              long_value, (long)0, (long)G_MAXUINT16);
            } else {
                arg->v_uint16 = long_value;
            }
569
            break;
570
        }
571

572
573
574
575
576
577
578
579
580
        case GI_TYPE_TAG_INT32:
        {
            long long_value = PyLong_AsLong (number);
            if (long_value < G_MININT32 || long_value > G_MAXINT32) {
                PyErr_Format (PyExc_ValueError, "%ld not in range %ld to %ld",
                              long_value, (long)G_MININT32, (long)G_MAXINT32);
            } else {
                arg->v_int32 = long_value;
            }
581
            break;
582
        }
583

584
585
586
587
588
589
590
591
592
        case GI_TYPE_TAG_UINT32:
        {
            PY_LONG_LONG long_value = PyLong_AsLongLong (number);
            if (long_value < 0 || long_value > G_MAXUINT32) {
                PyErr_Format (PyExc_ValueError, "%lld not in range %ld to %lu",
                              long_value, (long)0, (unsigned long)G_MAXUINT32);
            } else {
                arg->v_uint32 = long_value;
            }
593
            break;
594
        }
595

596
        case GI_TYPE_TAG_INT64:
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
        {
            /* Rely on Python overflow error and convert to ValueError for 64 bit values */
            gint64 value = PyLong_AsLongLong (number);
            if (PyErr_Occurred()) {
                if (PyErr_ExceptionMatches (PyExc_OverflowError)) {
                    PyErr_Clear();
#if PY_MAJOR_VERSION >= 3
                    PyErr_Format (PyExc_ValueError, "%S not in range %lld to %lld",
                                  number, PY_LLONG_MIN, PY_LLONG_MAX);
#else
                    /* Python 2.x does not support the %S format option and it is not
                     * worth the trouble to support this manually.
                     */
                    PyErr_Format (PyExc_ValueError, "number not in range %lld to %lld",
                                  PY_LLONG_MIN, PY_LLONG_MAX);
#endif
                }
            } else {
                arg->v_int64 = value;
            }
617
            break;
618
        }
619
620

        case GI_TYPE_TAG_UINT64:
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
        {
            /* Rely on Python overflow error and convert to ValueError for 64 bit values */
            guint64 value = PyLong_AsUnsignedLongLong (number);
            if (PyErr_Occurred()) {
                if (PyErr_ExceptionMatches (PyExc_OverflowError)) {
                    PyErr_Clear();
#if PY_MAJOR_VERSION >= 3
                    PyErr_Format (PyExc_ValueError, "%S not in range %ld to %llu",
                                  number, (long)0, PY_ULLONG_MAX);
#else
                    /* Python 2.x does not support the %S format option and it is not
                     * worth the trouble to support this manually.
                     */
                    PyErr_Format (PyExc_ValueError, "number not in range %ld to %llu",
                                  (long)0, PY_ULLONG_MAX);
#endif
                }
            } else {
                arg->v_uint64 = value;
            }
641
            break;
642
        }
643
644
645
646
647
648
649
650
651
652
653
654

        default:
            g_assert_not_reached ();
    }

    Py_DECREF (number);

    if (PyErr_Occurred())
        return FALSE;
    return TRUE;
}

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
gboolean
_pygi_marshal_from_py_basic_type (PyObject   *object,   /* in */
                                  GIArgument *arg,      /* out */
                                  GITypeTag   type_tag,
                                  GITransfer  transfer)
{
    switch (type_tag) {
        case GI_TYPE_TAG_VOID:
            g_warn_if_fail (transfer == GI_TRANSFER_NOTHING);
            if (object == Py_None) {
                arg->v_pointer = NULL;
            } else if (!PYGLIB_PyLong_Check(object)  && !PyLong_Check(object)) {
                PyErr_SetString(PyExc_TypeError,
                    "Pointer assignment is restricted to integer values. "
                    "See: https://bugzilla.gnome.org/show_bug.cgi?id=683599");
            } else {
                arg->v_pointer = PyLong_AsVoidPtr (object);
            }
            break;
        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_UINT8:
676
677
678
679
680
681
682
683
684
685
686
687
688
689
            if (PYGLIB_PyBytes_Check (object)) {
                if (PYGLIB_PyBytes_Size (object) != 1) {
                    PyErr_Format (PyExc_TypeError, "Must be a single character");
                    return FALSE;
                }
                if (type_tag == GI_TYPE_TAG_INT8) {
                    arg->v_int8 = (gint8)(PYGLIB_PyBytes_AsString (object)[0]);
                } else {
                    arg->v_uint8 = (guint8)(PYGLIB_PyBytes_AsString (object)[0]);
                }
            } else {
                return _pygi_marshal_from_py_long (object, arg, type_tag, transfer);
            }
            break;
690
        case GI_TYPE_TAG_INT16:
691
        case GI_TYPE_TAG_UINT16:
692
        case GI_TYPE_TAG_INT32:
693
        case GI_TYPE_TAG_UINT32:
694
        case GI_TYPE_TAG_INT64:
695
        case GI_TYPE_TAG_UINT64:
696
            return _pygi_marshal_from_py_long (object, arg, type_tag, transfer);
697

698
699
        case GI_TYPE_TAG_BOOLEAN:
            arg->v_boolean = PyObject_IsTrue (object);
700
            break;
701

702
        case GI_TYPE_TAG_FLOAT:
703
704
            return _pygi_marshal_from_py_float (object, arg);

705
        case GI_TYPE_TAG_DOUBLE:
706
707
            return _pygi_marshal_from_py_double (object, arg);

708
        case GI_TYPE_TAG_GTYPE:
709
            return _pygi_marshal_from_py_gtype (object, arg);
710
711

        case GI_TYPE_TAG_UNICHAR:
712
713
            return _pygi_marshal_from_py_unichar (object, arg);

714
        case GI_TYPE_TAG_UTF8:
715
716
            return _pygi_marshal_from_py_utf8 (object, arg);

717
        case GI_TYPE_TAG_FILENAME:
718
719
            return _pygi_marshal_from_py_filename (object, arg);

720
721
722
        default:
            return FALSE;
    }
723
724
725
726

    if (PyErr_Occurred())
        return FALSE;

727
728
729
    return TRUE;
}

730
731
732
733
734
735
736
737
738
739
740
741
gboolean
_pygi_marshal_from_py_basic_type_cache_adapter (PyGIInvokeState   *state,
                                                PyGICallableCache *callable_cache,
                                                PyGIArgCache      *arg_cache,
                                                PyObject          *py_arg,
                                                GIArgument        *arg)
{
    return _pygi_marshal_from_py_basic_type (py_arg,
                                             arg,
                                             arg_cache->type_tag,
                                             arg_cache->transfer);
}
742

743
gboolean
744
745
746
747
748
_pygi_marshal_from_py_array (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
749
{
750
    PyGIMarshalFromPyFunc from_py_marshaller;
751
    int i = 0;
752
    Py_ssize_t length;
753
    gssize item_size;
754
    gboolean is_ptr_array;
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
    GArray *array_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;


    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    length = PySequence_Length (py_arg);
    if (length < 0)
        return FALSE;

    if (sequence_cache->fixed_size >= 0 &&
        sequence_cache->fixed_size != length) {
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
                      sequence_cache->fixed_size, length);

        return FALSE;
    }

782
    item_size = sequence_cache->item_size;
783
784
785
786
787
788
    is_ptr_array = (sequence_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY);
    if (is_ptr_array) {
        array_ = (GArray *)g_ptr_array_new ();
    } else {
        array_ = g_array_sized_new (sequence_cache->is_zero_terminated,
                                    FALSE,
789
                                    item_size,
790
791
                                    length);
    }
792
793

    if (array_ == NULL) {
794
        PyErr_NoMemory ();
795
796
797
798
        return FALSE;
    }

    if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8 &&
799
800
        PYGLIB_PyBytes_Check (py_arg)) {
        memcpy(array_->data, PYGLIB_PyBytes_AsString (py_arg), length);
Martin Pitt's avatar
Martin Pitt committed
801
        array_->len = length;
802
803
804
805
806
        if (sequence_cache->is_zero_terminated) {
            /* If array_ has been created with zero_termination, space for the
             * terminator is properly allocated, so we're not off-by-one here. */
            array_->data[length] = '\0';
        }
807
808
809
        goto array_success;
    }

810
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
811
812
813
814
815
816
    for (i = 0; i < length; i++) {
        GIArgument item;
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

817
818
819
820
821
        if (!from_py_marshaller ( state,
                                  callable_cache,
                                  sequence_cache->item_cache,
                                  py_item,
                                 &item))
822
823
            goto err;

824
825
826
827
        /* FIXME: it is much more efficent to have seperate marshaller
         *        for ptr arrays than doing the evaluation
         *        and casting each loop iteration
         */
828
        if (is_ptr_array) {
829
            g_ptr_array_add((GPtrArray *)array_, item.v_pointer);
830
831
832
833
834
835
836
837
838
839
840
841
842
        } else if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_INTERFACE) {
            PyGIInterfaceCache *item_iface_cache = (PyGIInterfaceCache *) sequence_cache->item_cache;
            GIBaseInfo *base_info = (GIBaseInfo *) item_iface_cache->interface_info;
            GIInfoType info_type = g_base_info_get_type (base_info);

            switch (info_type) {
                case GI_INFO_TYPE_UNION:
                case GI_INFO_TYPE_STRUCT:
                {
                    PyGIArgCache *item_arg_cache = (PyGIArgCache *)item_iface_cache;
                    PyGIMarshalCleanupFunc from_py_cleanup = item_arg_cache->from_py_cleanup;
                    gboolean is_boxed = g_type_is_a (item_iface_cache->g_type, G_TYPE_BOXED);
                    gboolean is_gvalue = item_iface_cache->g_type == G_TYPE_VALUE;
843
844
845
846
847
848
849
                    gboolean is_gvariant = item_iface_cache->g_type == G_TYPE_VARIANT;
                    
                    if (is_gvariant) {
                        /* Item size will always be that of a pointer,
                         * since GVariants are opaque hence always passed by ref */
                        g_assert (item_size == sizeof (item.v_pointer));
                        g_array_insert_val (array_, i, item.v_pointer);
850
851
852
853
854
855
856
                    } else if (is_gvalue) {
                        GValue* dest = (GValue*) (array_->data + (i * item_size));
                        memset (dest, 0, item_size);
                        if (item.v_pointer != NULL) {
                            g_value_init (dest, G_VALUE_TYPE ((GValue*) item.v_pointer));
                            g_value_copy ((GValue*) item.v_pointer, dest);
                        }
Martin Pitt's avatar
Martin Pitt committed
857
858
859
                        /* we free the original copy already, the new one is a plain struct
                         * in an array. _pygi_marshal_cleanup_from_py_array() does not free it again */
                        if (from_py_cleanup)
860
861
                            from_py_cleanup (state, item_arg_cache, item.v_pointer, TRUE);
                    } else if (!is_boxed) {
862
863
864
865
866
867
868
869
870
871
872
873
874
875
                        /* HACK: Gdk.Atom is merely an integer wrapped in a pointer,
                         * so we must not dereference it; just copy the pointer
                         * value, and don't attempt to free it. TODO: find out
                         * if there are other data types with similar behaviour
                         * and generalize. */
                        if (g_strcmp0 (item_iface_cache->type_name, "Gdk.Atom") == 0) {
                            g_assert (item_size == sizeof (item.v_pointer));
                            memcpy (array_->data + (i * item_size), &item.v_pointer, item_size);
                        } else {
                            memcpy (array_->data + (i * item_size), item.v_pointer, item_size);

                            if (from_py_cleanup)
                                from_py_cleanup (state, item_arg_cache, item.v_pointer, TRUE);
                        }
876
877
878
879
880
881
                    } else if (is_boxed && !item_iface_cache->arg_cache.is_pointer) {
                        /* The array elements are not expected to be pointers, but the
                         * elements obtained are boxed pointers themselves, so insert
                         * the pointed to data.
                         */
                        g_array_insert_vals (array_, i, item.v_pointer, 1);
882
883
884
885
886
887
888
889
890
                    } else {
                        g_array_insert_val (array_, i, item);
                    }
                    break;
                }
                default:
                    g_array_insert_val (array_, i, item);
            }
        } else {
891
            g_array_insert_val (array_, i, item);
892
        }
893
894
        continue;
err:
895
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
896
897
            gsize j;
            PyGIMarshalCleanupFunc cleanup_func =
898
                sequence_cache->item_cache->from_py_cleanup;
899
900
901
902
903
904
905

            for(j = 0; j < i; j++) {
                cleanup_func (state,
                              sequence_cache->item_cache,
                              g_array_index (array_, gpointer, j),
                              TRUE);
            }
906
907
        }

908
        if (is_ptr_array)
909
            g_ptr_array_free ( ( GPtrArray *)array_, TRUE);
910
911
        else
            g_array_free (array_, TRUE);
912
913
914
915
916
917
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

array_success:
    if (sequence_cache->len_arg_index >= 0) {
918
919
        /* we have an child arg to handle */
        PyGIArgCache *child_cache =
920
            callable_cache->args_cache[sequence_cache->len_arg_index];
921

922
        if (child_cache->direction == PYGI_DIRECTION_BIDIRECTIONAL) {
923
            gint *len_arg = (gint *)state->in_args[child_cache->c_arg_index].v_pointer;
924
            /* if we are not setup yet just set the in arg */
David Malcolm's avatar
David Malcolm committed
925
926
927
928
929
930
931
            if (len_arg == NULL) {
                if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
                                                  length,
                                                  child_cache->type_tag)) {
                    goto err;
                }
            } else {
932
                *len_arg = length;
David Malcolm's avatar
David Malcolm committed
933
            }
934
        } else {
David Malcolm's avatar
David Malcolm committed
935
936
937
938
939
            if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
                                              length,
                                              child_cache->type_tag)) {
                goto err;
            }
940
941
942
943
944
        }
    }

    if (sequence_cache->array_type == GI_ARRAY_TYPE_C) {
        arg->v_pointer = array_->data;
945
        g_array_free (array_, FALSE);
Martin Pitt's avatar
Martin Pitt committed
946
947
948
949
        /* remember the originally allocated array in args_data, as args and
         * in_args get changed for (inout) arguments */
        if (arg_cache->transfer == GI_TRANSFER_NOTHING)
            state->args_data[arg_cache->c_arg_index] = arg->v_pointer;
950
951
952
953
954
955
956
957
    } else {
        arg->v_pointer = array_;
    }

    return TRUE;
}

gboolean
958
959
960
961
962
_pygi_marshal_from_py_glist (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
963
{
964
    PyGIMarshalFromPyFunc from_py_marshaller;
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
    int i;
    Py_ssize_t length;
    GList *list_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;


    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

982
    length = PySequence_Length (py_arg);
983
984
985
986
987
988
989
990
991
992
993
    if (length < 0)
        return FALSE;

    if (sequence_cache->fixed_size >= 0 &&
        sequence_cache->fixed_size != length) {
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
                      sequence_cache->fixed_size, length);

        return FALSE;
    }

994
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
995
996
997
998
999
1000
    for (i = 0; i < length; i++) {
        GIArgument item;
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

1001
1002
1003
1004
1005
        if (!from_py_marshaller ( state,
                                  callable_cache,
                                  sequence_cache->item_cache,
                                  py_item,
                                 &item))
1006
1007
            goto err;

1008
        list_ = g_list_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
1009
1010
        continue;
err:
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1011
        /* FIXME: clean up list
1012
1013
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
1014
        }
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1015
        */
1016
        g_list_free (list_);
1017
1018
1019
1020
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

1021
    arg->v_pointer = g_list_reverse (list_);
1022
1023
1024
1025
    return TRUE;
}

gboolean
1026
1027
1028
1029
1030
_pygi_marshal_from_py_gslist (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
1031
{
1032
    PyGIMarshalFromPyFunc from_py_marshaller;
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
    int i;
    Py_ssize_t length;
    GSList *list_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

1049
    length = PySequence_Length (py_arg);
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
    if (length < 0)
        return FALSE;

    if (sequence_cache->fixed_size >= 0 &&
        sequence_cache->fixed_size != length) {
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
                      sequence_cache->fixed_size, length);

        return FALSE;
    }

1061
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
1062
1063
1064
1065
1066
1067
    for (i = 0; i < length; i++) {
        GIArgument item;
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

1068
        if (!from_py_marshaller ( state,
1069
1070
1071
1072
                             callable_cache,
                             sequence_cache->item_cache,
                             py_item,
                            &item))
1073
1074
            goto err;

1075
        list_ = g_slist_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
1076
1077
        continue;
err:
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1078
        /* FIXME: Clean up list
1079
1080
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
1081
        }
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1082
        */
1083

1084
        g_slist_free (list_);
1085
1086
1087
1088
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

1089
    arg->v_pointer = g_slist_reverse (list_);
1090
1091
1092
1093
    return TRUE;
}

gboolean
1094
1095
1096
1097
1098
_pygi_marshal_from_py_ghash (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
1099
{
1100
1101
    PyGIMarshalFromPyFunc key_from_py_marshaller;
    PyGIMarshalFromPyFunc value_from_py_marshaller;
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117

    int i;
    Py_ssize_t length;
    PyObject *py_keys, *py_values;

    GHashFunc hash_func;
    GEqualFunc equal_func;

    GHashTable *hash_ = NULL;
    PyGIHashCache *hash_cache = (PyGIHashCache *)arg_cache;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

1118
    py_keys = PyMapping_Keys (py_arg);
1119
1120
1121
1122
1123
1124
    if (py_keys == NULL) {
        PyErr_Format (PyExc_TypeError, "Must be mapping, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

1125
    length = PyMapping_Length (py_arg);
1126
    if (length < 0) {
1127
        Py_DECREF (py_keys);
1128
1129
1130
        return FALSE;
    }

1131
    py_values = PyMapping_Values (py_arg);
1132
    if (py_values == NULL) {
1133
        Py_DECREF (py_keys);
1134
1135
1136
        return FALSE;
    }

1137
1138
    key_from_py_marshaller = hash_cache->key_cache->from_py_marshaller;
    value_from_py_marshaller = hash_cache->value_cache->from_py_marshaller;
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152

    switch (hash_cache->key_cache->type_tag) {
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
            hash_func = g_str_hash;
            equal_func = g_str_equal;
            break;
        default:
            hash_func = NULL;
            equal_func = NULL;
    }

    hash_ = g_hash_table_new (hash_func, equal_func);
    if (hash_ == NULL) {
1153
1154
1155
        PyErr_NoMemory ();
        Py_DECREF (py_keys);
        Py_DECREF (py_values);
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
        return FALSE;
    }

    for (i = 0; i < length; i++) {
        GIArgument key, value;
        PyObject *py_key = PyList_GET_ITEM (py_keys, i);
        PyObject *py_value = PyList_GET_ITEM (py_values, i);
        if (py_key == NULL || py_value == NULL)
            goto err;

1166
1167
1168
1169
1170
        if (!key_from_py_marshaller ( state,
                                      callable_cache,
                                      hash_cache->key_cache,
                                      py_key,
                                     &key))
1171
1172
            goto err;

1173
1174
1175
1176
1177
        if (!value_from_py_marshaller ( state,
                                        callable_cache,
                                        hash_cache->value_cache,
                                        py_value,
                                       &value))
1178
1179
            goto err;

1180
1181
1182
        g_hash_table_insert (hash_,
                             _pygi_arg_to_hash_pointer (&key, hash_cache->key_cache->type_tag),
                             _pygi_arg_to_hash_pointer (&value, hash_cache->value_cache->type_tag));
1183
1184
1185
        continue;
err:
        /* FIXME: cleanup hash keys and values */
1186
1187
1188
1189
1190
        Py_XDECREF (py_key);
        Py_XDECREF (py_value);
        Py_DECREF (py_keys);
        Py_DECREF (py_values);
        g_hash_table_unref (hash_);
1191
1192
1193
1194
1195
1196
1197
1198
1199
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

    arg->v_pointer = hash_;
    return TRUE;
}

gboolean
1200
1201
1202
1203
1204
_pygi_marshal_from_py_gerror (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
1205
{
1206
1207
    PyErr_Format (PyExc_NotImplementedError,
                  "Marshalling for GErrors is not implemented");
1208
1209
1210
    return FALSE;
}

1211
1212
1213
1214
1215
1216
1217
1218
1219
/* _pygi_destroy_notify_dummy:
 *
 * Dummy method used in the occasion when a method has a GDestroyNotify
 * argument without user data.
 */
static void
_pygi_destroy_notify_dummy (gpointer data) {
}

1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
static PyGICClosure *global_destroy_notify;

static void
_pygi_destroy_notify_callback_closure (ffi_cif *cif,
                                       void *result,
                                       void **args,
                                       void *data)
{
    PyGICClosure *info = * (void**) (args[0]);

    g_assert (info);

    _pygi_invoke_closure_free (info);
}

/* _pygi_destroy_notify_create:
 *
 * Method used in the occasion when a method has a GDestroyNotify
 * argument with user data.
 */
static PyGICClosure*
_pygi_destroy_notify_create (void)
{
    if (!global_destroy_notify) {

        PyGICClosure *destroy_notify = g_slice_new0 (PyGICClosure);
1246
        GIBaseInfo* glib_destroy_notify;
1247
1248
1249

        g_assert (destroy_notify);

1250
        glib_destroy_notify = g_irepository_find_by_name (NULL, "GLib", "DestroyNotify");
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
        g_assert (glib_destroy_notify != NULL);
        g_assert (g_base_info_get_type (glib_destroy_notify) == GI_INFO_TYPE_CALLBACK);

        destroy_notify->closure = g_callable_info_prepare_closure ( (GICallableInfo*) glib_destroy_notify,
                                                                    &destroy_notify->cif,
                                                                    _pygi_destroy_notify_callback_closure,
                                                                    NULL);

        global_destroy_notify = destroy_notify;
    }

    return global_destroy_notify;
}

1265
gboolean
1266
1267
1268
1269
1270
_pygi_marshal_from_py_interface_callback (PyGIInvokeState   *state,
                                          PyGICallableCache *callable_cache,
                                          PyGIArgCache      *arg_cache,
                                          PyObject          *py_arg,
                                          GIArgument        *arg)
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
{
    GICallableInfo *callable_info;
    PyGICClosure *closure;
    PyGIArgCache *user_data_cache = NULL;
    PyGIArgCache *destroy_cache = NULL;
    PyGICallbackCache *callback_cache;
    PyObject *py_user_data = NULL;

    callback_cache = (PyGICallbackCache *)arg_cache;

    if (callback_cache->user_data_index > 0) {
1282
        user_data_cache = callable_cache->args_cache[callback_cache->user_data_index];
1283
        if (user_data_cache->py_arg_index < state->n_py_in_args) {
1284
            /* py_user_data is a borrowed reference. */
1285
            py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
1286
1287
1288
1289
1290
1291
            if (!py_user_data)
                return FALSE;
        }
    }

    if (py_arg == Py_None && !(py_user_data == Py_None || py_user_data == NULL)) {
1292
1293
        PyErr_Format (PyExc_TypeError,
                      "When passing None for a callback userdata must also be None");
1294
1295
1296
1297
1298
1299
1300
1301

        return FALSE;
    }

    if (py_arg == Py_None) {
        return TRUE;
    }

1302
1303
1304
1305
    if (!PyCallable_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError,
                      "Callback needs to be a function or method not %s",
                      py_arg->ob_type->tp_name);
1306
1307
1308
1309
1310
1311
1312
1313

        return FALSE;
    }

    callable_info = (GICallableInfo *)callback_cache->interface_info;

    closure = _pygi_make_native_closure (callable_info, callback_cache->scope, py_arg, py_user_data);
    arg->v_pointer = closure->closure;
1314
1315
1316
1317

    /* The PyGICClosure instance is used as user data passed into the C function.
     * The return trip to python will marshal this back and pull the python user data out.
     */
1318
1319
1320
1321
    if (user_data_cache != NULL) {
        state->in_args[user_data_cache->c_arg_index].v_pointer = closure;
    }

1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
    /* Setup a GDestroyNotify callback if this method supports it along with
     * a user data field. The user data field is a requirement in order
     * free resources and ref counts associated with this arguments closure.
     * In case a user data field is not available, show a warning giving
     * explicit information and setup a dummy notification to avoid a crash
     * later on in _pygi_destroy_notify_callback_closure.
     */
    if (callback_cache->destroy_notify_index > 0) {
        destroy_cache = callable_cache->args_cache[callback_cache->destroy_notify_index];
    }

1333
    if (destroy_cache) {
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
        if (user_data_cache != NULL) {
            PyGICClosure *destroy_notify = _pygi_destroy_notify_create ();
            state->in_args[destroy_cache->c_arg_index].v_pointer = destroy_notify->closure;
        } else {
            gchar *msg = g_strdup_printf("Callables passed to %s will leak references because "
                                         "the method does not support a user_data argument. "
                                         "See: https://bugzilla.gnome.org/show_bug.cgi?id=685598",
                                         callable_cache->name);
            if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 2)) {
                g_free(msg);
                _pygi_invoke_closure_free(closure);
                return FALSE;
            }
            g_free(msg);
            state->in_args[destroy_cache->c_arg_index].v_pointer = _pygi_destroy_notify_dummy;
        }
1350
1351
    }

1352
1353
1354
1355
1356
    /* Store the PyGIClosure as extra args data so _pygi_marshal_cleanup_from_py_interface_callback
     * can clean it up later for GI_SCOPE_TYPE_CALL based closures.
     */
    state->args_data[arg_cache->c_arg_index] = closure;

1357
1358
1359
1360
    return TRUE;
}

gboolean
1361
1362
1363
1364
1365
_pygi_marshal_from_py_interface_enum (PyGIInvokeState   *state,
                                      PyGICallableCache *callable_cache,
                                      PyGIArgCache      *arg_cache,
                                      PyObject          *py_arg,
                                      GIArgument        *arg)
1366
{
David Malcolm's avatar
David Malcolm committed
1367
1368
    PyObject *py_long;
    long c_long;
1369
1370
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
1371
    GIBaseInfo *interface = NULL;
1372

1373
    is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
1374

David Malcolm's avatar
David Malcolm committed
1375
1376
    py_long = PYGLIB_PyNumber_Long (py_arg);
    if (py_long == NULL) {
1377
1378
1379
1380
        PyErr_Clear();
        goto err;
    }

David Malcolm's avatar
David Malcolm committed
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
    c_long = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);

    /* Write c_long into arg */
    interface = g_type_info_get_interface (arg_cache->type_info);
    assert(g_base_info_get_type (interface) == GI_INFO_TYPE_ENUM);
    if (!gi_argument_from_c_long(arg,
                                 c_long,
                                 g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
          g_assert_not_reached();
1391
          g_base_info_unref (interface);
David Malcolm's avatar
David Malcolm committed
1392
1393
          return FALSE;
    }
1394
1395
1396
1397
1398
1399
1400
1401

    /* If this is not an instance of the Enum type that we want
     * we need to check if the value is equivilant to one of the
     * Enum's memebers */
    if (!is_instance) {
        int i;
        gboolean is_found = FALSE;

1402
        for (i = 0; i < g_enum_info_get_n_values (iface_cache->interface_info); i++) {
1403
            GIValueInfo *value_info =
1404
1405
1406
                g_enum_info_get_value (iface_cache->interface_info, i);
            glong enum_value = g_value_info_get_value (value_info);
            g_base_info_unref ( (GIBaseInfo *)value_info);
David Malcolm's avatar
David Malcolm committed
1407
            if (c_long == enum_value) {
1408
1409
1410
1411
1412
1413
1414
1415
1416
                is_found = TRUE;
                break;
            }
        }

        if (!is_found)
            goto err;
    }

1417
    g_base_info_unref (interface);
1418
1419
1420
    return TRUE;

err:
1421
1422
    if (interface)
        g_base_info_unref (interface);
1423
1424
    PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
                  iface_cache->type_name, py_arg->ob_type->tp_name);
1425
1426
1427
1428
    return FALSE;
}

gboolean
1429
1430
1431
1432
1433
_pygi_marshal_from_py_interface_flags (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
                                       GIArgument        *arg)
1434
{
David Malcolm's avatar
David Malcolm committed
1435
1436
    PyObject *py_long;
    long c_long;
1437
1438
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
David Malcolm's avatar
David Malcolm committed
1439
    GIBaseInfo *interface;