4ddfbb47e626f47aad19b8b367e7318c2590b233
[platform/upstream/pygobject2.git] / gi / pygi-marshal-from-py.c
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2  * vim: tabstop=4 shiftwidth=4 expandtab
3  *
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  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
21  * USA
22  */
23
24 #include "pygi-private.h"
25
26 #include <string.h>
27 #include <time.h>
28 #include <pygobject.h>
29 #include <pyglib-python-compat.h>
30
31 #include "pygi-cache.h"
32 #include "pygi-marshal-cleanup.h"
33 #include "pygi-marshal-from-py.h"
34
35 gboolean
36 gi_argument_from_py_ssize_t (GIArgument   *arg_out,
37                              Py_ssize_t    size_in,
38                              GITypeTag     type_tag)                             
39 {
40     switch (type_tag) {
41     case GI_TYPE_TAG_VOID:
42     case GI_TYPE_TAG_BOOLEAN:
43         goto unhandled_type;
44
45     case GI_TYPE_TAG_INT8:
46         if (size_in >= G_MININT8 && size_in <= G_MAXINT8) {
47             arg_out->v_int8 = size_in;
48             return TRUE;
49         } else {
50             goto overflow;
51         }
52
53     case GI_TYPE_TAG_UINT8:
54         if (size_in >= 0 && size_in <= G_MAXUINT8) {
55             arg_out->v_uint8 = size_in;
56             return TRUE;
57         } else {
58             goto overflow;
59         }
60
61     case GI_TYPE_TAG_INT16:
62         if (size_in >= G_MININT16 && size_in <= G_MAXINT16) {
63             arg_out->v_int16 = size_in;
64             return TRUE;
65         } else {
66             goto overflow;
67         }
68
69     case GI_TYPE_TAG_UINT16:
70         if (size_in >= 0 && size_in <= G_MAXUINT16) {
71             arg_out->v_uint16 = size_in;
72             return TRUE;
73         } else {
74             goto overflow;
75         }
76
77         /* Ranges assume two's complement */
78     case GI_TYPE_TAG_INT32:
79         if (size_in >= G_MININT32 && size_in <= G_MAXINT32) {
80             arg_out->v_int32 = size_in;
81             return TRUE;
82         } else {
83             goto overflow;
84         }
85
86     case GI_TYPE_TAG_UINT32:
87         if (size_in >= 0 && size_in <= G_MAXUINT32) {
88             arg_out->v_uint32 = size_in;
89             return TRUE;
90         } else {
91             goto overflow;
92         }
93
94     case GI_TYPE_TAG_INT64:
95         arg_out->v_int64 = size_in;
96         return TRUE;
97
98     case GI_TYPE_TAG_UINT64:
99         if (size_in >= 0) {
100             arg_out->v_uint64 = size_in;
101             return TRUE;
102         } else {
103             goto overflow;
104         }
105             
106     case GI_TYPE_TAG_FLOAT:
107     case GI_TYPE_TAG_DOUBLE:
108     case GI_TYPE_TAG_GTYPE:
109     case GI_TYPE_TAG_UTF8:
110     case GI_TYPE_TAG_FILENAME:
111     case GI_TYPE_TAG_ARRAY:
112     case GI_TYPE_TAG_INTERFACE:
113     case GI_TYPE_TAG_GLIST:
114     case GI_TYPE_TAG_GSLIST:
115     case GI_TYPE_TAG_GHASH:
116     case GI_TYPE_TAG_ERROR:
117     case GI_TYPE_TAG_UNICHAR:
118     default:
119         goto unhandled_type;
120     }
121
122  overflow:
123     PyErr_Format (PyExc_OverflowError,
124                   "Unable to marshal C Py_ssize_t %zd to %s",
125                   size_in,
126                   g_type_tag_to_string (type_tag));
127     return FALSE;
128
129  unhandled_type:
130     PyErr_Format (PyExc_TypeError,
131                   "Unable to marshal C Py_ssize_t %zd to %s",
132                   size_in,
133                   g_type_tag_to_string (type_tag));
134     return FALSE;
135 }
136
137 gboolean
138 gi_argument_from_c_long (GIArgument *arg_out,
139                          long        c_long_in,
140                          GITypeTag   type_tag)
141 {
142     switch (type_tag) {
143       case GI_TYPE_TAG_INT8:
144           arg_out->v_int8 = c_long_in;
145           return TRUE;
146       case GI_TYPE_TAG_UINT8:
147           arg_out->v_uint8 = c_long_in;
148           return TRUE;
149       case GI_TYPE_TAG_INT16:
150           arg_out->v_int16 = c_long_in;
151           return TRUE;
152       case GI_TYPE_TAG_UINT16:
153           arg_out->v_uint16 = c_long_in;
154           return TRUE;
155       case GI_TYPE_TAG_INT32:
156           arg_out->v_int32 = c_long_in;
157           return TRUE;
158       case GI_TYPE_TAG_UINT32:
159           arg_out->v_uint32 = c_long_in;
160           return TRUE;
161       case GI_TYPE_TAG_INT64:
162           arg_out->v_int64 = c_long_in;
163           return TRUE;
164       case GI_TYPE_TAG_UINT64:
165           arg_out->v_uint64 = c_long_in;
166           return TRUE;
167       default:
168           PyErr_Format (PyExc_TypeError,
169                         "Unable to marshal C long %ld to %s",
170                         c_long_in,
171                         g_type_tag_to_string (type_tag));
172           return FALSE;
173     }
174 }
175
176 /*
177  * _is_union_member - check to see if the py_arg is actually a member of the
178  * expected C union
179  */
180 static gboolean
181 _is_union_member (PyGIInterfaceCache *iface_cache, PyObject *py_arg) {
182     gint i;
183     gint n_fields;
184     GIUnionInfo *union_info;
185     GIInfoType info_type;
186     gboolean is_member = FALSE;
187
188     info_type = g_base_info_get_type (iface_cache->interface_info);
189
190     if (info_type != GI_INFO_TYPE_UNION)
191         return FALSE;
192
193     union_info = (GIUnionInfo *) iface_cache->interface_info;
194     n_fields = g_union_info_get_n_fields (union_info);
195
196     for (i = 0; i < n_fields; i++) {
197         GIFieldInfo *field_info;
198         GITypeInfo *field_type_info;
199
200         field_info = g_union_info_get_field (union_info, i);
201         field_type_info = g_field_info_get_type (field_info);
202
203         /* we can only check if the members are interfaces */
204         if (g_type_info_get_tag (field_type_info) == GI_TYPE_TAG_INTERFACE) {
205             GIInterfaceInfo *field_iface_info;
206             PyObject *py_type;
207
208             field_iface_info = g_type_info_get_interface (field_type_info);
209             py_type = _pygi_type_import_by_gi_info ((GIBaseInfo *) field_iface_info);
210
211             if (py_type != NULL && PyObject_IsInstance (py_arg, py_type)) {
212                 is_member = TRUE;
213             }
214
215             Py_XDECREF (py_type);
216             g_base_info_unref ( ( GIBaseInfo *) field_iface_info);
217         }
218
219         g_base_info_unref ( ( GIBaseInfo *) field_type_info);
220         g_base_info_unref ( ( GIBaseInfo *) field_info);
221
222         if (is_member)
223             break;
224     }
225
226     return is_member;
227 }
228
229 gboolean
230 _pygi_marshal_from_py_void (PyGIInvokeState   *state,
231                             PyGICallableCache *callable_cache,
232                             PyGIArgCache      *arg_cache,
233                             PyObject          *py_arg,
234                             GIArgument        *arg)
235 {
236     g_warn_if_fail (arg_cache->transfer == GI_TRANSFER_NOTHING);
237
238     arg->v_pointer = py_arg;
239
240     return TRUE;
241 }
242
243 gboolean
244 _pygi_marshal_from_py_boolean (PyGIInvokeState   *state,
245                                PyGICallableCache *callable_cache,
246                                PyGIArgCache      *arg_cache,
247                                PyObject          *py_arg,
248                                GIArgument        *arg)
249 {
250     arg->v_boolean = PyObject_IsTrue (py_arg);
251
252     return TRUE;
253 }
254
255 gboolean
256 _pygi_marshal_from_py_int8 (PyGIInvokeState   *state,
257                             PyGICallableCache *callable_cache,
258                             PyGIArgCache      *arg_cache,
259                             PyObject          *py_arg,
260                             GIArgument        *arg)
261 {
262     PyObject *py_long;
263     long long_;
264
265     if (PYGLIB_PyBytes_Check (py_arg)) {
266
267         if (PYGLIB_PyBytes_Size (py_arg) != 1) {
268             PyErr_Format (PyExc_TypeError, "Must be a single character");
269             return FALSE;
270         }
271
272         long_ = (char)(PYGLIB_PyBytes_AsString (py_arg)[0]);
273     } else if (PyNumber_Check (py_arg)) {
274         py_long = PYGLIB_PyNumber_Long (py_arg);
275         if (!py_long)
276             return FALSE;
277
278         long_ = PYGLIB_PyLong_AsLong (py_long);
279         Py_DECREF (py_long);
280
281         if (PyErr_Occurred ()) {
282             PyErr_Clear ();
283             PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -128, 127);
284             return FALSE;
285         }
286     } else {
287         PyErr_Format (PyExc_TypeError, "Must be number or single byte string, not %s",
288                       py_arg->ob_type->tp_name);
289         return FALSE;
290     }
291
292     if (long_ < -128 || long_ > 127) {
293         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -128, 127);
294         return FALSE;
295     }
296
297     arg->v_int8 = long_;
298
299     return TRUE;
300 }
301
302 gboolean
303 _pygi_marshal_from_py_uint8 (PyGIInvokeState   *state,
304                              PyGICallableCache *callable_cache,
305                              PyGIArgCache      *arg_cache,
306                              PyObject          *py_arg,
307                              GIArgument        *arg)
308 {
309     unsigned long long_;
310
311     if (PYGLIB_PyBytes_Check (py_arg)) {
312
313         if (PYGLIB_PyBytes_Size (py_arg) != 1) {
314             PyErr_Format (PyExc_TypeError, "Must be a single character");
315             return FALSE;
316         }
317
318         long_ = (unsigned char)(PYGLIB_PyBytes_AsString (py_arg)[0]);
319
320     } else if (PyNumber_Check (py_arg)) {
321         PyObject *py_long;
322         py_long = PYGLIB_PyNumber_Long (py_arg);
323         if (!py_long)
324             return FALSE;
325
326         long_ = PYGLIB_PyLong_AsLong (py_long);
327         Py_DECREF (py_long);
328
329         if (PyErr_Occurred ()) {
330             PyErr_Clear();
331
332             PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 255);
333             return FALSE;
334         }
335     } else {
336         PyErr_Format (PyExc_TypeError, "Must be number or single byte string, not %s",
337                       py_arg->ob_type->tp_name);
338         return FALSE;
339     }
340
341     if (long_ < 0 || long_ > 255) {
342         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 255);
343         return FALSE;
344     }
345
346     arg->v_uint8 = long_;
347
348     return TRUE;
349 }
350
351 gboolean
352 _pygi_marshal_from_py_int16 (PyGIInvokeState   *state,
353                              PyGICallableCache *callable_cache,
354                              PyGIArgCache      *arg_cache,
355                              PyObject          *py_arg,
356                              GIArgument        *arg)
357 {
358     PyObject *py_long;
359     long long_;
360
361     if (!PyNumber_Check (py_arg)) {
362         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
363                       py_arg->ob_type->tp_name);
364         return FALSE;
365     }
366
367     py_long = PYGLIB_PyNumber_Long (py_arg);
368     if (!py_long)
369         return FALSE;
370
371     long_ = PYGLIB_PyLong_AsLong (py_long);
372     Py_DECREF (py_long);
373
374     if (PyErr_Occurred ()) {
375         PyErr_Clear ();
376         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -32768, 32767);
377         return FALSE;
378     }
379
380     if (long_ < -32768 || long_ > 32767) {
381         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -32768, 32767);
382         return FALSE;
383     }
384
385     arg->v_int16 = long_;
386
387     return TRUE;
388 }
389
390 gboolean
391 _pygi_marshal_from_py_uint16 (PyGIInvokeState   *state,
392                               PyGICallableCache *callable_cache,
393                               PyGIArgCache      *arg_cache,
394                               PyObject          *py_arg,
395                               GIArgument        *arg)
396 {
397     PyObject *py_long;
398     long long_;
399
400     if (!PyNumber_Check (py_arg)) {
401         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
402                       py_arg->ob_type->tp_name);
403         return FALSE;
404     }
405
406     py_long = PYGLIB_PyNumber_Long (py_arg);
407     if (!py_long)
408         return FALSE;
409
410     long_ = PYGLIB_PyLong_AsLong (py_long);
411     Py_DECREF (py_long);
412
413     if (PyErr_Occurred ()) {
414         PyErr_Clear ();
415         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 65535);
416         return FALSE;
417     }
418
419     if (long_ < 0 || long_ > 65535) {
420         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 65535);
421         return FALSE;
422     }
423
424     arg->v_uint16 = long_;
425
426     return TRUE;
427 }
428
429 gboolean
430 _pygi_marshal_from_py_int32 (PyGIInvokeState   *state,
431                              PyGICallableCache *callable_cache,
432                              PyGIArgCache      *arg_cache,
433                              PyObject          *py_arg,
434                              GIArgument        *arg)
435 {
436     PyObject *py_long;
437     long long_;
438
439     if (!PyNumber_Check (py_arg)) {
440         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
441                       py_arg->ob_type->tp_name);
442         return FALSE;
443     }
444
445     py_long = PYGLIB_PyNumber_Long (py_arg);
446     if (!py_long)
447         return FALSE;
448
449     long_ = PYGLIB_PyLong_AsLong (py_long);
450     Py_DECREF (py_long);
451
452     if (PyErr_Occurred ()) {
453         PyErr_Clear();
454         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, G_MININT32, G_MAXINT32);
455         return FALSE;
456     }
457
458     if (long_ < G_MININT32 || long_ > G_MAXINT32) {
459         PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, G_MININT32, G_MAXINT32);
460         return FALSE;
461     }
462
463     arg->v_int32 = long_;
464
465     return TRUE;
466 }
467
468 gboolean
469 _pygi_marshal_from_py_uint32 (PyGIInvokeState   *state,
470                               PyGICallableCache *callable_cache,
471                               PyGIArgCache      *arg_cache,
472                               PyObject          *py_arg,
473                               GIArgument        *arg)
474 {
475     PyObject *py_long;
476     long long long_;
477
478     if (!PyNumber_Check (py_arg)) {
479         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
480                       py_arg->ob_type->tp_name);
481         return FALSE;
482     }
483
484     py_long = PYGLIB_PyNumber_Long (py_arg);
485     if (!py_long)
486         return FALSE;
487
488 #if PY_VERSION_HEX < 0x03000000
489     if (PyInt_Check (py_long))
490         long_ = PyInt_AsLong (py_long);
491     else
492 #endif
493         long_ = PyLong_AsLongLong (py_long);
494
495     Py_DECREF (py_long);
496
497     if (PyErr_Occurred ()) {
498         PyErr_Clear ();
499         PyErr_Format (PyExc_ValueError, "%lld not in range %i to %u", long_, 0, G_MAXUINT32);
500         return FALSE;
501     }
502
503     if (long_ < 0 || long_ > G_MAXUINT32) {
504         PyErr_Format (PyExc_ValueError, "%lld not in range %i to %u", long_, 0, G_MAXUINT32);
505         return FALSE;
506     }
507
508     arg->v_uint32 = long_;
509
510     return TRUE;
511 }
512
513 gboolean
514 _pygi_marshal_from_py_int64 (PyGIInvokeState   *state,
515                              PyGICallableCache *callable_cache,
516                              PyGIArgCache      *arg_cache,
517                              PyObject          *py_arg,
518                              GIArgument        *arg)
519 {
520     PyObject *py_long;
521     gint64 long_;
522
523     if (!PyNumber_Check (py_arg)) {
524         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
525                       py_arg->ob_type->tp_name);
526         return FALSE;
527     }
528
529     py_long = PYGLIB_PyNumber_Long (py_arg);
530     if (!py_long)
531         return FALSE;
532
533 #if PY_VERSION_HEX < 0x03000000
534     if (PyInt_Check (py_long))
535         long_ = (gint64) PyInt_AS_LONG (py_long);
536     else
537 #endif
538         long_ = (gint64) PyLong_AsLongLong (py_long);
539
540     Py_DECREF (py_long);
541
542     if (PyErr_Occurred ()) {
543         /* OverflowError occured but range errors should be returned as ValueError */
544         char *long_str;
545         PyObject *py_str;
546
547         PyErr_Clear ();
548
549         py_str = PyObject_Str (py_long);
550
551         if (PyUnicode_Check (py_str)) {
552             PyObject *py_bytes = PyUnicode_AsUTF8String (py_str);
553             Py_DECREF (py_str);
554
555             if (py_bytes == NULL)
556                 return FALSE;
557
558             long_str = g_strdup (PYGLIB_PyBytes_AsString (py_bytes));
559             if (long_str == NULL) {
560                 PyErr_NoMemory ();
561                 return FALSE;
562             }
563
564             Py_DECREF (py_bytes);
565         } else {
566             long_str = g_strdup (PYGLIB_PyBytes_AsString(py_str));
567             Py_DECREF (py_str);
568         }
569
570         PyErr_Format (PyExc_ValueError, "%s not in range %lld to %lld",
571                       long_str, (long long) G_MININT64, (long long) G_MAXINT64);
572
573         g_free (long_str);
574         return FALSE;
575     }
576
577     arg->v_int64 = long_;
578
579     return TRUE;
580 }
581
582 gboolean
583 _pygi_marshal_from_py_uint64 (PyGIInvokeState   *state,
584                               PyGICallableCache *callable_cache,
585                               PyGIArgCache      *arg_cache,
586                               PyObject          *py_arg,
587                               GIArgument        *arg)
588 {
589     PyObject *py_long;
590     guint64 ulong_;
591
592     if (!PyNumber_Check (py_arg)) {
593         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
594                       py_arg->ob_type->tp_name);
595         return FALSE;
596     }
597
598     py_long = PYGLIB_PyNumber_Long (py_arg);
599     if (!py_long)
600         return FALSE;
601
602 #if PY_VERSION_HEX < 0x03000000
603     if (PyInt_Check (py_long)) {
604         long long_ =  PyInt_AsLong (py_long);
605         if (long_ < 0 || long_ > G_MAXUINT64) {
606             PyErr_Format (PyExc_ValueError, "%" G_GUINT64_FORMAT " not in range %d to %" G_GUINT64_FORMAT,
607                           (gint64) long_, 0, G_MAXUINT64);
608             return FALSE;
609         }
610         ulong_ = (guint64) long_;
611     } else
612 #endif
613         ulong_ = PyLong_AsUnsignedLongLong (py_long);
614
615     Py_DECREF (py_long);
616
617     if (PyErr_Occurred ()) {
618         /* OverflowError occured but range errors should be returned as ValueError */
619         char *long_str;
620         PyObject *py_str;
621
622         PyErr_Clear ();
623
624         py_str = PyObject_Str (py_long);
625
626         if (PyUnicode_Check (py_str)) {
627             PyObject *py_bytes = PyUnicode_AsUTF8String (py_str);
628             Py_DECREF (py_str);
629
630             if (py_bytes == NULL)
631                 return FALSE;
632
633             long_str = g_strdup (PYGLIB_PyBytes_AsString (py_bytes));
634             if (long_str == NULL) {
635                 PyErr_NoMemory ();
636                 return FALSE;
637             }
638
639             Py_DECREF (py_bytes);
640         } else {
641             long_str = g_strdup (PYGLIB_PyBytes_AsString (py_str));
642             Py_DECREF (py_str);
643         }
644
645         PyErr_Format (PyExc_ValueError, "%s not in range %d to %" G_GUINT64_FORMAT,
646                       long_str, 0, G_MAXUINT64);
647
648         g_free (long_str);
649         return FALSE;
650     }
651
652     if (ulong_ > G_MAXUINT64) {
653         PyErr_Format (PyExc_ValueError, "%" G_GUINT64_FORMAT " not in range %d to %" G_GUINT64_FORMAT, ulong_, 0, G_MAXUINT64);
654         return FALSE;
655     }
656
657     arg->v_uint64 = ulong_;
658
659     return TRUE;
660 }
661
662 gboolean
663 _pygi_marshal_from_py_float (PyGIInvokeState   *state,
664                              PyGICallableCache *callable_cache,
665                              PyGIArgCache      *arg_cache,
666                              PyObject          *py_arg,
667                              GIArgument        *arg)
668 {
669     PyObject *py_float;
670     double double_;
671
672     if (!PyNumber_Check (py_arg)) {
673         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
674                       py_arg->ob_type->tp_name);
675         return FALSE;
676     }
677
678     py_float = PyNumber_Float (py_arg);
679     if (!py_float)
680         return FALSE;
681
682     double_ = PyFloat_AsDouble (py_float);
683     Py_DECREF (py_float);
684
685     if (PyErr_Occurred ()) {
686         PyErr_Clear ();
687         PyErr_Format (PyExc_ValueError, "%f not in range %f to %f", double_, -G_MAXFLOAT, G_MAXFLOAT);
688         return FALSE;
689     }
690
691     if (double_ < -G_MAXFLOAT || double_ > G_MAXFLOAT) {
692         PyErr_Format (PyExc_ValueError, "%f not in range %f to %f", double_, -G_MAXFLOAT, G_MAXFLOAT);
693         return FALSE;
694     }
695
696     arg->v_float = double_;
697
698     return TRUE;
699 }
700
701 gboolean
702 _pygi_marshal_from_py_double (PyGIInvokeState   *state,
703                               PyGICallableCache *callable_cache,
704                               PyGIArgCache      *arg_cache,
705                               PyObject          *py_arg,
706                               GIArgument        *arg)
707 {
708     PyObject *py_float;
709     double double_;
710
711     if (!PyNumber_Check (py_arg)) {
712         PyErr_Format (PyExc_TypeError, "Must be number, not %s",
713                       py_arg->ob_type->tp_name);
714         return FALSE;
715     }
716
717     py_float = PyNumber_Float (py_arg);
718     if (!py_float)
719         return FALSE;
720
721     double_ = PyFloat_AsDouble (py_float);
722     Py_DECREF (py_float);
723
724     if (PyErr_Occurred ()) {
725         PyErr_Clear ();
726         PyErr_Format (PyExc_ValueError, "%f not in range %f to %f", double_, -G_MAXDOUBLE, G_MAXDOUBLE);
727         return FALSE;
728     }
729
730     if (double_ < -G_MAXDOUBLE || double_ > G_MAXDOUBLE) {
731         PyErr_Format (PyExc_ValueError, "%f not in range %f to %f", double_, -G_MAXDOUBLE, G_MAXDOUBLE);
732         return FALSE;
733     }
734
735     arg->v_double = double_;
736
737     return TRUE;
738 }
739
740 gboolean
741 _pygi_marshal_from_py_unichar (PyGIInvokeState   *state,
742                                PyGICallableCache *callable_cache,
743                                PyGIArgCache      *arg_cache,
744                                PyObject          *py_arg,
745                                GIArgument        *arg)
746 {
747     Py_ssize_t size;
748     gchar *string_;
749
750     if (PyUnicode_Check (py_arg)) {
751        PyObject *py_bytes;
752
753        size = PyUnicode_GET_SIZE (py_arg);
754        py_bytes = PyUnicode_AsUTF8String (py_arg);
755        string_ = strdup(PYGLIB_PyBytes_AsString (py_bytes));
756        Py_DECREF (py_bytes);
757
758 #if PY_VERSION_HEX < 0x03000000
759     } else if (PyString_Check (py_arg)) {
760        PyObject *pyuni = PyUnicode_FromEncodedObject (py_arg, "UTF-8", "strict");
761        if (!pyuni)
762            return FALSE;
763
764        size = PyUnicode_GET_SIZE (pyuni);
765        string_ = g_strdup (PyString_AsString(py_arg));
766        Py_DECREF (pyuni);
767 #endif
768     } else {
769        PyErr_Format (PyExc_TypeError, "Must be string, not %s",
770                      py_arg->ob_type->tp_name);
771        return FALSE;
772     }
773
774     if (size != 1) {
775        PyErr_Format (PyExc_TypeError, "Must be a one character string, not %lld characters",
776                      (long long) size);
777        g_free (string_);
778        return FALSE;
779     }
780
781     arg->v_uint32 = g_utf8_get_char (string_);
782     g_free (string_);
783
784     return TRUE;
785 }
786 gboolean
787 _pygi_marshal_from_py_gtype (PyGIInvokeState   *state,
788                              PyGICallableCache *callable_cache,
789                              PyGIArgCache      *arg_cache,
790                              PyObject          *py_arg,
791                              GIArgument        *arg)
792 {
793     long type_ = pyg_type_from_object (py_arg);
794
795     if (type_ == 0) {
796         PyErr_Format (PyExc_TypeError, "Must be gobject.GType, not %s",
797                       py_arg->ob_type->tp_name);
798         return FALSE;
799     }
800
801     arg->v_long = type_;
802     return TRUE;
803 }
804 gboolean
805 _pygi_marshal_from_py_utf8 (PyGIInvokeState   *state,
806                             PyGICallableCache *callable_cache,
807                             PyGIArgCache      *arg_cache,
808                             PyObject          *py_arg,
809                             GIArgument        *arg)
810 {
811     gchar *string_;
812
813     if (py_arg == Py_None) {
814         arg->v_pointer = NULL;
815         return TRUE;
816     }
817
818     if (PyUnicode_Check (py_arg)) {
819         PyObject *pystr_obj = PyUnicode_AsUTF8String (py_arg);
820         if (!pystr_obj)
821             return FALSE;
822
823         string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj));
824         Py_DECREF (pystr_obj);
825     }
826 #if PY_VERSION_HEX < 0x03000000
827     else if (PyString_Check (py_arg)) {
828         string_ = g_strdup (PyString_AsString (py_arg));
829     }
830 #endif
831     else {
832         PyErr_Format (PyExc_TypeError, "Must be string, not %s",
833                       py_arg->ob_type->tp_name);
834         return FALSE;
835     }
836
837     arg->v_string = string_;
838     return TRUE;
839 }
840
841 gboolean
842 _pygi_marshal_from_py_filename (PyGIInvokeState   *state,
843                                 PyGICallableCache *callable_cache,
844                                 PyGIArgCache      *arg_cache,
845                                 PyObject          *py_arg,
846                                 GIArgument        *arg)
847 {
848     gchar *string_;
849     GError *error = NULL;
850
851     if (PyUnicode_Check (py_arg)) {
852         PyObject *pystr_obj = PyUnicode_AsUTF8String (py_arg);
853         if (!pystr_obj)
854             return FALSE;
855
856         string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj));
857         Py_DECREF (pystr_obj);
858     }
859 #if PY_VERSION_HEX < 0x03000000
860     else if (PyString_Check (py_arg)) {
861         string_ = g_strdup (PyString_AsString (py_arg));
862     }
863 #endif
864     else {
865         PyErr_Format (PyExc_TypeError, "Must be string, not %s",
866                       py_arg->ob_type->tp_name);
867         return FALSE;
868     }
869
870     arg->v_string = g_filename_from_utf8 (string_, -1, NULL, NULL, &error);
871     g_free (string_);
872
873     if (arg->v_string == NULL) {
874         PyErr_SetString (PyExc_Exception, error->message);
875         g_error_free (error);
876         /* TODO: Convert the error to an exception. */
877         return FALSE;
878     }
879
880     return TRUE;
881 }
882
883 gboolean
884 _pygi_marshal_from_py_array (PyGIInvokeState   *state,
885                              PyGICallableCache *callable_cache,
886                              PyGIArgCache      *arg_cache,
887                              PyObject          *py_arg,
888                              GIArgument        *arg)
889 {
890     PyGIMarshalFromPyFunc from_py_marshaller;
891     int i;
892     Py_ssize_t length;
893     gssize item_size;
894     gboolean is_ptr_array;
895     GArray *array_ = NULL;
896     PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;
897
898
899     if (py_arg == Py_None) {
900         arg->v_pointer = NULL;
901         return TRUE;
902     }
903
904     if (!PySequence_Check (py_arg)) {
905         PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
906                       py_arg->ob_type->tp_name);
907         return FALSE;
908     }
909
910     length = PySequence_Length (py_arg);
911     if (length < 0)
912         return FALSE;
913
914     if (sequence_cache->fixed_size >= 0 &&
915         sequence_cache->fixed_size != length) {
916         PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
917                       sequence_cache->fixed_size, length);
918
919         return FALSE;
920     }
921
922     item_size = sequence_cache->item_size;
923     is_ptr_array = (sequence_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY);
924     if (is_ptr_array) {
925         array_ = (GArray *)g_ptr_array_new ();
926     } else {
927         array_ = g_array_sized_new (sequence_cache->is_zero_terminated,
928                                     FALSE,
929                                     item_size,
930                                     length);
931     }
932
933     if (array_ == NULL) {
934         PyErr_NoMemory ();
935         return FALSE;
936     }
937
938     if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8 &&
939         PYGLIB_PyBytes_Check (py_arg)) {
940         memcpy(array_->data, PYGLIB_PyBytes_AsString (py_arg), length);
941         array_->len = length;
942         if (sequence_cache->is_zero_terminated) {
943             /* If array_ has been created with zero_termination, space for the
944              * terminator is properly allocated, so we're not off-by-one here. */
945             array_->data[length] = '\0';
946         }
947         goto array_success;
948     }
949
950     from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
951     for (i = 0; i < length; i++) {
952         GIArgument item;
953         PyObject *py_item = PySequence_GetItem (py_arg, i);
954         if (py_item == NULL)
955             goto err;
956
957         if (!from_py_marshaller ( state,
958                                   callable_cache,
959                                   sequence_cache->item_cache,
960                                   py_item,
961                                  &item))
962             goto err;
963
964         /* FIXME: it is much more efficent to have seperate marshaller
965          *        for ptr arrays than doing the evaluation
966          *        and casting each loop iteration
967          */
968         if (is_ptr_array) {
969             g_ptr_array_add((GPtrArray *)array_, item.v_pointer);
970         } else if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_INTERFACE) {
971             PyGIInterfaceCache *item_iface_cache = (PyGIInterfaceCache *) sequence_cache->item_cache;
972             GIBaseInfo *base_info = (GIBaseInfo *) item_iface_cache->interface_info;
973             GIInfoType info_type = g_base_info_get_type (base_info);
974
975             switch (info_type) {
976                 case GI_INFO_TYPE_UNION:
977                 case GI_INFO_TYPE_STRUCT:
978                 {
979                     PyGIArgCache *item_arg_cache = (PyGIArgCache *)item_iface_cache;
980                     PyGIMarshalCleanupFunc from_py_cleanup = item_arg_cache->from_py_cleanup;
981                     gboolean is_boxed = g_type_is_a (item_iface_cache->g_type, G_TYPE_BOXED);
982                     gboolean is_gvalue = item_iface_cache->g_type == G_TYPE_VALUE;
983                     gboolean is_gvariant = item_iface_cache->g_type == G_TYPE_VARIANT;
984                     
985                     if (is_gvariant) {
986                         /* Item size will always be that of a pointer,
987                          * since GVariants are opaque hence always passed by ref */
988                         g_assert (item_size == sizeof (item.v_pointer));
989                         g_array_insert_val (array_, i, item.v_pointer);
990                     } else if (is_gvalue) {
991                         GValue* dest = (GValue*) (array_->data + (i * item_size));
992                         memset (dest, 0, item_size);
993                         if (item.v_pointer != NULL) {
994                             g_value_init (dest, G_VALUE_TYPE ((GValue*) item.v_pointer));
995                             g_value_copy ((GValue*) item.v_pointer, dest);
996                         }
997
998                         if (from_py_cleanup) {
999                             from_py_cleanup (state, item_arg_cache, item.v_pointer, TRUE);
1000                             /* we freed the original copy already, the new one is a 
1001                              * struct in an array. _pygi_marshal_cleanup_from_py_array()
1002                              * must not free it again */
1003                             item_arg_cache->from_py_cleanup = NULL;
1004                         }
1005                     } else if (!is_boxed) {
1006                         /* HACK: Gdk.Atom is merely an integer wrapped in a pointer,
1007                          * so we must not dereference it; just copy the pointer
1008                          * value, and don't attempt to free it. TODO: find out
1009                          * if there are other data types with similar behaviour
1010                          * and generalize. */
1011                         if (g_strcmp0 (item_iface_cache->type_name, "Gdk.Atom") == 0) {
1012                             g_assert (item_size == sizeof (item.v_pointer));
1013                             memcpy (array_->data + (i * item_size), &item.v_pointer, item_size);
1014                         } else {
1015                             memcpy (array_->data + (i * item_size), item.v_pointer, item_size);
1016
1017                             if (from_py_cleanup)
1018                                 from_py_cleanup (state, item_arg_cache, item.v_pointer, TRUE);
1019                         }
1020                     } else if (is_boxed && !item_iface_cache->arg_cache.is_pointer) {
1021                         /* The array elements are not expected to be pointers, but the
1022                          * elements obtained are boxed pointers themselves, so insert
1023                          * the pointed to data.
1024                          */
1025                         g_array_insert_vals (array_, i, item.v_pointer, 1);
1026                     } else {
1027                         g_array_insert_val (array_, i, item);
1028                     }
1029                     break;
1030                 }
1031                 default:
1032                     g_array_insert_val (array_, i, item);
1033             }
1034         } else {
1035             g_array_insert_val (array_, i, item);
1036         }
1037         continue;
1038 err:
1039         if (sequence_cache->item_cache->from_py_cleanup != NULL) {
1040             gsize j;
1041             PyGIMarshalCleanupFunc cleanup_func =
1042                 sequence_cache->item_cache->from_py_cleanup;
1043
1044             for(j = 0; j < i; j++) {
1045                 cleanup_func (state,
1046                               sequence_cache->item_cache,
1047                               g_array_index (array_, gpointer, j),
1048                               TRUE);
1049             }
1050         }
1051
1052         if (is_ptr_array)
1053             g_ptr_array_free ( ( GPtrArray *)array_, TRUE);
1054         else
1055             g_array_free (array_, TRUE);
1056         _PyGI_ERROR_PREFIX ("Item %i: ", i);
1057         return FALSE;
1058     }
1059
1060 array_success:
1061     if (sequence_cache->len_arg_index >= 0) {
1062         /* we have an child arg to handle */
1063         PyGIArgCache *child_cache =
1064             callable_cache->args_cache[sequence_cache->len_arg_index];
1065
1066         if (child_cache->direction == PYGI_DIRECTION_BIDIRECTIONAL) {
1067             gint *len_arg = (gint *)state->in_args[child_cache->c_arg_index].v_pointer;
1068             /* if we are not setup yet just set the in arg */
1069             if (len_arg == NULL) {
1070                 if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
1071                                                   length,
1072                                                   child_cache->type_tag)) {
1073                     goto err;
1074                 }
1075             } else {
1076                 *len_arg = length;
1077             }
1078         } else {
1079             if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
1080                                               length,
1081                                               child_cache->type_tag)) {
1082                 goto err;
1083             }
1084         }
1085     }
1086
1087     if (sequence_cache->array_type == GI_ARRAY_TYPE_C) {
1088         arg->v_pointer = array_->data;
1089         g_array_free (array_, FALSE);
1090     } else {
1091         arg->v_pointer = array_;
1092     }
1093
1094     return TRUE;
1095 }
1096
1097 gboolean
1098 _pygi_marshal_from_py_glist (PyGIInvokeState   *state,
1099                              PyGICallableCache *callable_cache,
1100                              PyGIArgCache      *arg_cache,
1101                              PyObject          *py_arg,
1102                              GIArgument        *arg)
1103 {
1104     PyGIMarshalFromPyFunc from_py_marshaller;
1105     int i;
1106     Py_ssize_t length;
1107     GList *list_ = NULL;
1108     PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;
1109
1110
1111     if (py_arg == Py_None) {
1112         arg->v_pointer = NULL;
1113         return TRUE;
1114     }
1115
1116     if (!PySequence_Check (py_arg)) {
1117         PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
1118                       py_arg->ob_type->tp_name);
1119         return FALSE;
1120     }
1121
1122     length = PySequence_Length (py_arg);
1123     if (length < 0)
1124         return FALSE;
1125
1126     if (sequence_cache->fixed_size >= 0 &&
1127         sequence_cache->fixed_size != length) {
1128         PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
1129                       sequence_cache->fixed_size, length);
1130
1131         return FALSE;
1132     }
1133
1134     from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
1135     for (i = 0; i < length; i++) {
1136         GIArgument item;
1137         PyObject *py_item = PySequence_GetItem (py_arg, i);
1138         if (py_item == NULL)
1139             goto err;
1140
1141         if (!from_py_marshaller ( state,
1142                                   callable_cache,
1143                                   sequence_cache->item_cache,
1144                                   py_item,
1145                                  &item))
1146             goto err;
1147
1148         list_ = g_list_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
1149         continue;
1150 err:
1151         /* FIXME: clean up list
1152         if (sequence_cache->item_cache->from_py_cleanup != NULL) {
1153             PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
1154         }
1155         */
1156         g_list_free (list_);
1157         _PyGI_ERROR_PREFIX ("Item %i: ", i);
1158         return FALSE;
1159     }
1160
1161     arg->v_pointer = g_list_reverse (list_);
1162     return TRUE;
1163 }
1164
1165 gboolean
1166 _pygi_marshal_from_py_gslist (PyGIInvokeState   *state,
1167                               PyGICallableCache *callable_cache,
1168                               PyGIArgCache      *arg_cache,
1169                               PyObject          *py_arg,
1170                               GIArgument        *arg)
1171 {
1172     PyGIMarshalFromPyFunc from_py_marshaller;
1173     int i;
1174     Py_ssize_t length;
1175     GSList *list_ = NULL;
1176     PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;
1177
1178     if (py_arg == Py_None) {
1179         arg->v_pointer = NULL;
1180         return TRUE;
1181     }
1182
1183     if (!PySequence_Check (py_arg)) {
1184         PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
1185                       py_arg->ob_type->tp_name);
1186         return FALSE;
1187     }
1188
1189     length = PySequence_Length (py_arg);
1190     if (length < 0)
1191         return FALSE;
1192
1193     if (sequence_cache->fixed_size >= 0 &&
1194         sequence_cache->fixed_size != length) {
1195         PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
1196                       sequence_cache->fixed_size, length);
1197
1198         return FALSE;
1199     }
1200
1201     from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
1202     for (i = 0; i < length; i++) {
1203         GIArgument item;
1204         PyObject *py_item = PySequence_GetItem (py_arg, i);
1205         if (py_item == NULL)
1206             goto err;
1207
1208         if (!from_py_marshaller ( state,
1209                              callable_cache,
1210                              sequence_cache->item_cache,
1211                              py_item,
1212                             &item))
1213             goto err;
1214
1215         list_ = g_slist_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
1216         continue;
1217 err:
1218         /* FIXME: Clean up list
1219         if (sequence_cache->item_cache->from_py_cleanup != NULL) {
1220             PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
1221         }
1222         */
1223
1224         g_slist_free (list_);
1225         _PyGI_ERROR_PREFIX ("Item %i: ", i);
1226         return FALSE;
1227     }
1228
1229     arg->v_pointer = g_slist_reverse (list_);
1230     return TRUE;
1231 }
1232
1233 gboolean
1234 _pygi_marshal_from_py_ghash (PyGIInvokeState   *state,
1235                              PyGICallableCache *callable_cache,
1236                              PyGIArgCache      *arg_cache,
1237                              PyObject          *py_arg,
1238                              GIArgument        *arg)
1239 {
1240     PyGIMarshalFromPyFunc key_from_py_marshaller;
1241     PyGIMarshalFromPyFunc value_from_py_marshaller;
1242
1243     int i;
1244     Py_ssize_t length;
1245     PyObject *py_keys, *py_values;
1246
1247     GHashFunc hash_func;
1248     GEqualFunc equal_func;
1249
1250     GHashTable *hash_ = NULL;
1251     PyGIHashCache *hash_cache = (PyGIHashCache *)arg_cache;
1252
1253     if (py_arg == Py_None) {
1254         arg->v_pointer = NULL;
1255         return TRUE;
1256     }
1257
1258     py_keys = PyMapping_Keys (py_arg);
1259     if (py_keys == NULL) {
1260         PyErr_Format (PyExc_TypeError, "Must be mapping, not %s",
1261                       py_arg->ob_type->tp_name);
1262         return FALSE;
1263     }
1264
1265     length = PyMapping_Length (py_arg);
1266     if (length < 0) {
1267         Py_DECREF (py_keys);
1268         return FALSE;
1269     }
1270
1271     py_values = PyMapping_Values (py_arg);
1272     if (py_values == NULL) {
1273         Py_DECREF (py_keys);
1274         return FALSE;
1275     }
1276
1277     key_from_py_marshaller = hash_cache->key_cache->from_py_marshaller;
1278     value_from_py_marshaller = hash_cache->value_cache->from_py_marshaller;
1279
1280     switch (hash_cache->key_cache->type_tag) {
1281         case GI_TYPE_TAG_UTF8:
1282         case GI_TYPE_TAG_FILENAME:
1283             hash_func = g_str_hash;
1284             equal_func = g_str_equal;
1285             break;
1286         default:
1287             hash_func = NULL;
1288             equal_func = NULL;
1289     }
1290
1291     hash_ = g_hash_table_new (hash_func, equal_func);
1292     if (hash_ == NULL) {
1293         PyErr_NoMemory ();
1294         Py_DECREF (py_keys);
1295         Py_DECREF (py_values);
1296         return FALSE;
1297     }
1298
1299     for (i = 0; i < length; i++) {
1300         GIArgument key, value;
1301         PyObject *py_key = PyList_GET_ITEM (py_keys, i);
1302         PyObject *py_value = PyList_GET_ITEM (py_values, i);
1303         if (py_key == NULL || py_value == NULL)
1304             goto err;
1305
1306         if (!key_from_py_marshaller ( state,
1307                                       callable_cache,
1308                                       hash_cache->key_cache,
1309                                       py_key,
1310                                      &key))
1311             goto err;
1312
1313         if (!value_from_py_marshaller ( state,
1314                                         callable_cache,
1315                                         hash_cache->value_cache,
1316                                         py_value,
1317                                        &value))
1318             goto err;
1319
1320         g_hash_table_insert (hash_,
1321                              _pygi_arg_to_hash_pointer (&key, hash_cache->key_cache->type_tag),
1322                              _pygi_arg_to_hash_pointer (&value, hash_cache->value_cache->type_tag));
1323         continue;
1324 err:
1325         /* FIXME: cleanup hash keys and values */
1326         Py_XDECREF (py_key);
1327         Py_XDECREF (py_value);
1328         Py_DECREF (py_keys);
1329         Py_DECREF (py_values);
1330         g_hash_table_unref (hash_);
1331         _PyGI_ERROR_PREFIX ("Item %i: ", i);
1332         return FALSE;
1333     }
1334
1335     arg->v_pointer = hash_;
1336     return TRUE;
1337 }
1338
1339 gboolean
1340 _pygi_marshal_from_py_gerror (PyGIInvokeState   *state,
1341                               PyGICallableCache *callable_cache,
1342                               PyGIArgCache      *arg_cache,
1343                               PyObject          *py_arg,
1344                               GIArgument        *arg)
1345 {
1346     PyErr_Format (PyExc_NotImplementedError,
1347                   "Marshalling for GErrors is not implemented");
1348     return FALSE;
1349 }
1350
1351 /* _pygi_destroy_notify_dummy:
1352  *
1353  * Dummy method used in the occasion when a method has a GDestroyNotify
1354  * argument without user data.
1355  */
1356 static void
1357 _pygi_destroy_notify_dummy (gpointer data) {
1358 }
1359
1360 static PyGICClosure *global_destroy_notify;
1361
1362 static void
1363 _pygi_destroy_notify_callback_closure (ffi_cif *cif,
1364                                        void *result,
1365                                        void **args,
1366                                        void *data)
1367 {
1368     PyGICClosure *info = * (void**) (args[0]);
1369
1370     g_assert (info);
1371
1372     _pygi_invoke_closure_free (info);
1373 }
1374
1375 /* _pygi_destroy_notify_create:
1376  *
1377  * Method used in the occasion when a method has a GDestroyNotify
1378  * argument with user data.
1379  */
1380 static PyGICClosure*
1381 _pygi_destroy_notify_create (void)
1382 {
1383     if (!global_destroy_notify) {
1384
1385         PyGICClosure *destroy_notify = g_slice_new0 (PyGICClosure);
1386
1387         g_assert (destroy_notify);
1388
1389         GIBaseInfo* glib_destroy_notify = g_irepository_find_by_name (NULL, "GLib", "DestroyNotify");
1390         g_assert (glib_destroy_notify != NULL);
1391         g_assert (g_base_info_get_type (glib_destroy_notify) == GI_INFO_TYPE_CALLBACK);
1392
1393         destroy_notify->closure = g_callable_info_prepare_closure ( (GICallableInfo*) glib_destroy_notify,
1394                                                                     &destroy_notify->cif,
1395                                                                     _pygi_destroy_notify_callback_closure,
1396                                                                     NULL);
1397
1398         global_destroy_notify = destroy_notify;
1399     }
1400
1401     return global_destroy_notify;
1402 }
1403
1404 gboolean
1405 _pygi_marshal_from_py_interface_callback (PyGIInvokeState   *state,
1406                                           PyGICallableCache *callable_cache,
1407                                           PyGIArgCache      *arg_cache,
1408                                           PyObject          *py_arg,
1409                                           GIArgument        *arg)
1410 {
1411     GICallableInfo *callable_info;
1412     PyGICClosure *closure;
1413     PyGIArgCache *user_data_cache = NULL;
1414     PyGIArgCache *destroy_cache = NULL;
1415     PyGICallbackCache *callback_cache;
1416     PyObject *py_user_data = NULL;
1417
1418     callback_cache = (PyGICallbackCache *)arg_cache;
1419
1420     if (callback_cache->user_data_index > 0) {
1421         user_data_cache = callable_cache->args_cache[callback_cache->user_data_index];
1422         if (user_data_cache->py_arg_index < state->n_py_in_args) {
1423             /* py_user_data is a borrowed reference. */
1424             py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
1425             if (!py_user_data)
1426                 return FALSE;
1427         }
1428     }
1429
1430     if (py_arg == Py_None && !(py_user_data == Py_None || py_user_data == NULL)) {
1431         PyErr_Format (PyExc_TypeError,
1432                       "When passing None for a callback userdata must also be None");
1433
1434         return FALSE;
1435     }
1436
1437     if (py_arg == Py_None) {
1438         return TRUE;
1439     }
1440
1441     if (!PyCallable_Check (py_arg)) {
1442         PyErr_Format (PyExc_TypeError,
1443                       "Callback needs to be a function or method not %s",
1444                       py_arg->ob_type->tp_name);
1445
1446         return FALSE;
1447     }
1448
1449     callable_info = (GICallableInfo *)callback_cache->interface_info;
1450
1451     closure = _pygi_make_native_closure (callable_info, callback_cache->scope, py_arg, py_user_data);
1452     arg->v_pointer = closure->closure;
1453
1454     /* The PyGICClosure instance is used as user data passed into the C function.
1455      * The return trip to python will marshal this back and pull the python user data out.
1456      */
1457     if (user_data_cache != NULL) {
1458         state->in_args[user_data_cache->c_arg_index].v_pointer = closure;
1459     }
1460
1461     /* Setup a GDestroyNotify callback if this method supports it along with
1462      * a user data field. The user data field is a requirement in order
1463      * free resources and ref counts associated with this arguments closure.
1464      * In case a user data field is not available, show a warning giving
1465      * explicit information and setup a dummy notification to avoid a crash
1466      * later on in _pygi_destroy_notify_callback_closure.
1467      */
1468     if (callback_cache->destroy_notify_index > 0) {
1469         destroy_cache = callable_cache->args_cache[callback_cache->destroy_notify_index];
1470     }
1471
1472     if (destroy_cache) {
1473         if (user_data_cache != NULL) {
1474             PyGICClosure *destroy_notify = _pygi_destroy_notify_create ();
1475             state->in_args[destroy_cache->c_arg_index].v_pointer = destroy_notify->closure;
1476         } else {
1477             gchar *msg = g_strdup_printf("Callables passed to %s will leak references because "
1478                                          "the method does not support a user_data argument. "
1479                                          "See: https://bugzilla.gnome.org/show_bug.cgi?id=685598",
1480                                          callable_cache->name);
1481             if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 2)) {
1482                 g_free(msg);
1483                 _pygi_invoke_closure_free(closure);
1484                 return FALSE;
1485             }
1486             g_free(msg);
1487             state->in_args[destroy_cache->c_arg_index].v_pointer = _pygi_destroy_notify_dummy;
1488         }
1489     }
1490
1491     /* Store the PyGIClosure as extra args data so _pygi_marshal_cleanup_from_py_interface_callback
1492      * can clean it up later for GI_SCOPE_TYPE_CALL based closures.
1493      */
1494     state->args_data[arg_cache->c_arg_index] = closure;
1495
1496     return TRUE;
1497 }
1498
1499 gboolean
1500 _pygi_marshal_from_py_interface_enum (PyGIInvokeState   *state,
1501                                       PyGICallableCache *callable_cache,
1502                                       PyGIArgCache      *arg_cache,
1503                                       PyObject          *py_arg,
1504                                       GIArgument        *arg)
1505 {
1506     PyObject *py_long;
1507     long c_long;
1508     gint is_instance;
1509     PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
1510     GIBaseInfo *interface;
1511
1512     is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
1513
1514     py_long = PYGLIB_PyNumber_Long (py_arg);
1515     if (py_long == NULL) {
1516         PyErr_Clear();
1517         goto err;
1518     }
1519
1520     c_long = PYGLIB_PyLong_AsLong (py_long);
1521     Py_DECREF (py_long);
1522
1523     /* Write c_long into arg */
1524     interface = g_type_info_get_interface (arg_cache->type_info);
1525     assert(g_base_info_get_type (interface) == GI_INFO_TYPE_ENUM);
1526     if (!gi_argument_from_c_long(arg,
1527                                  c_long,
1528                                  g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
1529           g_assert_not_reached();
1530           return FALSE;
1531     }
1532
1533     /* If this is not an instance of the Enum type that we want
1534      * we need to check if the value is equivilant to one of the
1535      * Enum's memebers */
1536     if (!is_instance) {
1537         int i;
1538         gboolean is_found = FALSE;
1539
1540         for (i = 0; i < g_enum_info_get_n_values (iface_cache->interface_info); i++) {
1541             GIValueInfo *value_info =
1542                 g_enum_info_get_value (iface_cache->interface_info, i);
1543             glong enum_value = g_value_info_get_value (value_info);
1544             g_base_info_unref ( (GIBaseInfo *)value_info);
1545             if (c_long == enum_value) {
1546                 is_found = TRUE;
1547                 break;
1548             }
1549         }
1550
1551         if (!is_found)
1552             goto err;
1553     }
1554
1555     return TRUE;
1556
1557 err:
1558     PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
1559                   iface_cache->type_name, py_arg->ob_type->tp_name);
1560     return FALSE;
1561 }
1562
1563 gboolean
1564 _pygi_marshal_from_py_interface_flags (PyGIInvokeState   *state,
1565                                        PyGICallableCache *callable_cache,
1566                                        PyGIArgCache      *arg_cache,
1567                                        PyObject          *py_arg,
1568                                        GIArgument        *arg)
1569 {
1570     PyObject *py_long;
1571     long c_long;
1572     gint is_instance;
1573     PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
1574     GIBaseInfo *interface;
1575
1576     is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
1577
1578     py_long = PYGLIB_PyNumber_Long (py_arg);
1579     if (py_long == NULL) {
1580         PyErr_Clear ();
1581         goto err;
1582     }
1583
1584     c_long = PYGLIB_PyLong_AsLong (py_long);
1585     Py_DECREF (py_long);
1586
1587     /* only 0 or argument of type Flag is allowed */
1588     if (!is_instance && c_long != 0)
1589         goto err;
1590
1591     /* Write c_long into arg */
1592     interface = g_type_info_get_interface (arg_cache->type_info);
1593     g_assert (g_base_info_get_type (interface) == GI_INFO_TYPE_FLAGS);
1594     if (!gi_argument_from_c_long(arg, c_long,
1595                                  g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
1596         return FALSE;
1597     }
1598
1599     return TRUE;
1600
1601 err:
1602     PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
1603                   iface_cache->type_name, py_arg->ob_type->tp_name);
1604     return FALSE;
1605
1606 }
1607
1608 gboolean
1609 _pygi_marshal_from_py_interface_struct (PyGIInvokeState   *state,
1610                                         PyGICallableCache *callable_cache,
1611                                         PyGIArgCache      *arg_cache,
1612                                         PyObject          *py_arg,
1613                                         GIArgument        *arg)
1614 {
1615     PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
1616
1617     if (py_arg == Py_None) {
1618         arg->v_pointer = NULL;
1619         return TRUE;
1620     }
1621
1622     /* FIXME: handle this large if statement in the cache
1623      *        and set the correct marshaller
1624      */
1625
1626     if (iface_cache->g_type == G_TYPE_CLOSURE) {
1627         GClosure *closure;
1628         GType object_gtype = pyg_type_from_object_strict (py_arg, FALSE);
1629
1630         if ( !(PyCallable_Check(py_arg) || 
1631                g_type_is_a (object_gtype, G_TYPE_CLOSURE))) {
1632             PyErr_Format (PyExc_TypeError, "Must be callable, not %s",
1633                           py_arg->ob_type->tp_name);
1634             return FALSE;
1635         }
1636
1637         if (g_type_is_a (object_gtype, G_TYPE_CLOSURE))
1638             closure = (GClosure *)pyg_boxed_get (py_arg, void);
1639         else
1640             closure = pyg_closure_new (py_arg, NULL, NULL);
1641
1642         if (closure == NULL) {
1643             PyErr_SetString (PyExc_RuntimeError, "PyObject conversion to GClosure failed");
1644             return FALSE;
1645         }
1646
1647         arg->v_pointer = closure;
1648         return TRUE;
1649     } else if (iface_cache->g_type == G_TYPE_VALUE) {
1650         GValue *value;
1651         GType object_type;
1652
1653         object_type = pyg_type_from_object_strict ( (PyObject *) py_arg->ob_type, FALSE);
1654         if (object_type == G_TYPE_INVALID) {
1655             PyErr_SetString (PyExc_RuntimeError, "unable to retrieve object's GType");
1656             return FALSE;
1657         }
1658
1659         /* if already a gvalue, use that, else marshal into gvalue */
1660         if (object_type == G_TYPE_VALUE) {
1661             value = (GValue *)( (PyGObject *)py_arg)->obj;
1662         } else {
1663             value = g_slice_new0 (GValue);
1664             g_value_init (value, object_type);
1665             if (pyg_value_from_pyobject (value, py_arg) < 0) {
1666                 g_slice_free (GValue, value);
1667                 PyErr_SetString (PyExc_RuntimeError, "PyObject conversion to GValue failed");
1668                 return FALSE;
1669             }
1670         }
1671
1672         arg->v_pointer = value;
1673         return TRUE;
1674     } else if (iface_cache->is_foreign) {
1675         PyObject *success;
1676         success = pygi_struct_foreign_convert_to_g_argument (py_arg,
1677                                                              iface_cache->interface_info,
1678                                                              arg_cache->transfer,
1679                                                              arg);
1680
1681         return (success == Py_None);
1682     } else if (!PyObject_IsInstance (py_arg, iface_cache->py_type)) {
1683         /* first check to see if this is a member of the expected union */
1684         if (!_is_union_member (iface_cache, py_arg)) {
1685             if (!PyErr_Occurred()) {
1686                 PyObject *module = PyObject_GetAttrString(py_arg, "__module__");
1687
1688                 PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s",
1689                               arg_cache->arg_name ? arg_cache->arg_name : "self",
1690                               iface_cache->type_name,
1691                               module ? PYGLIB_PyUnicode_AsString(module) : "",
1692                               module ? "." : "",
1693                               py_arg->ob_type->tp_name);
1694                 if (module)
1695                     Py_DECREF (module);
1696             }
1697
1698             return FALSE;
1699         }
1700     }
1701
1702     if (g_type_is_a (iface_cache->g_type, G_TYPE_BOXED)) {
1703         arg->v_pointer = pyg_boxed_get (py_arg, void);
1704         if (arg_cache->transfer == GI_TRANSFER_EVERYTHING) {
1705             arg->v_pointer = g_boxed_copy (iface_cache->g_type, arg->v_pointer);
1706         }
1707     } else if (g_type_is_a (iface_cache->g_type, G_TYPE_POINTER) ||
1708                    g_type_is_a (iface_cache->g_type, G_TYPE_VARIANT) ||
1709                        iface_cache->g_type  == G_TYPE_NONE) {
1710         arg->v_pointer = pyg_pointer_get (py_arg, void);
1711     } else {
1712         PyErr_Format (PyExc_NotImplementedError,
1713                       "structure type '%s' is not supported yet",
1714                       g_type_name(iface_cache->g_type));
1715         return FALSE;
1716     }
1717     return TRUE;
1718 }
1719
1720 gboolean
1721 _pygi_marshal_from_py_interface_boxed (PyGIInvokeState   *state,
1722                                        PyGICallableCache *callable_cache,
1723                                        PyGIArgCache      *arg_cache,
1724                                        PyObject          *py_arg,
1725                                        GIArgument        *arg)
1726 {
1727     PyErr_Format (PyExc_NotImplementedError,
1728                   "Marshalling for this type is not implemented yet");
1729     return FALSE;
1730 }
1731
1732 gboolean
1733 _pygi_marshal_from_py_interface_object (PyGIInvokeState   *state,
1734                                         PyGICallableCache *callable_cache,
1735                                         PyGIArgCache      *arg_cache,
1736                                         PyObject          *py_arg,
1737                                         GIArgument        *arg)
1738 {
1739     if (py_arg == Py_None) {
1740         arg->v_pointer = NULL;
1741         return TRUE;
1742     }
1743
1744     if (!PyObject_IsInstance (py_arg, ( (PyGIInterfaceCache *)arg_cache)->py_type)) {
1745         PyObject *module = PyObject_GetAttrString(py_arg, "__module__");
1746
1747         PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s",
1748                       arg_cache->arg_name ? arg_cache->arg_name : "self",
1749                       ( (PyGIInterfaceCache *)arg_cache)->type_name,
1750                       module ? PYGLIB_PyUnicode_AsString(module) : "",
1751                       module ? "." : "",
1752                       py_arg->ob_type->tp_name);
1753         if (module)
1754             Py_DECREF (module);
1755         return FALSE;
1756     }
1757
1758     arg->v_pointer = pygobject_get(py_arg);
1759     if (arg_cache->transfer == GI_TRANSFER_EVERYTHING)
1760         g_object_ref (arg->v_pointer);
1761
1762     return TRUE;
1763 }
1764
1765 gboolean
1766 _pygi_marshal_from_py_interface_union (PyGIInvokeState   *state,
1767                                        PyGICallableCache *callable_cache,
1768                                        PyGIArgCache      *arg_cache,
1769                                        PyObject          *py_arg,
1770                                        GIArgument        *arg)
1771 {
1772     PyErr_Format(PyExc_NotImplementedError,
1773                  "Marshalling for this type is not implemented yet");
1774     return FALSE;
1775 }
1776
1777 gboolean _pygi_marshal_from_py_interface_instance (PyGIInvokeState   *state,
1778                                                    PyGICallableCache *callable_cache,
1779                                                    PyGIArgCache      *arg_cache,
1780                                                    PyObject          *py_arg,
1781                                                    GIArgument        *arg)
1782 {
1783     GIInfoType info_type;
1784     PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
1785
1786     info_type = g_base_info_get_type (iface_cache->interface_info);
1787     switch (info_type) {
1788         case GI_INFO_TYPE_UNION:
1789         case GI_INFO_TYPE_STRUCT:
1790         {
1791             GType type = iface_cache->g_type;
1792
1793             if (!PyObject_IsInstance (py_arg, iface_cache->py_type)) {
1794                 /* wait, we might be a member of a union so manually check */
1795                 if (!_is_union_member (iface_cache, py_arg)) {
1796                     if (!PyErr_Occurred()) {
1797                         PyObject *module = PyObject_GetAttrString(py_arg, "__module__");
1798                         PyErr_Format (PyExc_TypeError,
1799                                       "argument %s: Expected a %s, but got %s%s%s",
1800                                       arg_cache->arg_name ? arg_cache->arg_name : "self",
1801                                       iface_cache->type_name,
1802                                       module ? PYGLIB_PyUnicode_AsString(module) : "",
1803                                       module ? "." : "",
1804                                       py_arg->ob_type->tp_name);
1805                         if (module)
1806                             Py_DECREF (module);
1807                     }
1808                     return FALSE;
1809                 }
1810             }
1811
1812             if (g_type_is_a (type, G_TYPE_BOXED)) {
1813                 arg->v_pointer = pyg_boxed_get (py_arg, void);
1814             } else if (g_type_is_a (type, G_TYPE_POINTER) ||
1815                            g_type_is_a (type, G_TYPE_VARIANT) ||
1816                                type == G_TYPE_NONE) {
1817                 arg->v_pointer = pyg_pointer_get (py_arg, void);
1818             } else {
1819                  PyErr_Format (PyExc_TypeError, "unable to convert an instance of '%s'", g_type_name (type));
1820                  return FALSE;
1821             }
1822
1823             break;
1824         }
1825         case GI_INFO_TYPE_OBJECT:
1826         case GI_INFO_TYPE_INTERFACE:
1827             arg->v_pointer = pygobject_get (py_arg);
1828             if (arg->v_pointer != NULL) {
1829                 GType obj_type = G_OBJECT_TYPE (( GObject *)arg->v_pointer);
1830                 GType expected_type = iface_cache->g_type;
1831
1832                 if (!g_type_is_a (obj_type, expected_type)) {
1833                     PyObject *module = PyObject_GetAttrString(py_arg, "__module__");
1834                     PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s",
1835                                   arg_cache->arg_name ? arg_cache->arg_name : "self",
1836                                   iface_cache->type_name,
1837                                   module ? PYGLIB_PyUnicode_AsString(module) : "",
1838                                   module ? "." : "",
1839                                   py_arg->ob_type->tp_name);
1840                     if (module)
1841                         Py_DECREF (module);
1842                     return FALSE;
1843                 }
1844             }
1845             break;
1846         default:
1847             /* Other types don't have methods. */
1848             g_assert_not_reached ();
1849    }
1850
1851    return TRUE;
1852 }