pygi-marshal-from-py.c 27.9 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
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;
    }
}

90 91 92 93 94
/*
 * _is_union_member - check to see if the py_arg is actually a member of the
 * expected C union
 */
static gboolean
95
_is_union_member (GIInterfaceInfo *interface_info, PyObject *py_arg) {
96 97 98 99 100 101
    gint i;
    gint n_fields;
    GIUnionInfo *union_info;
    GIInfoType info_type;
    gboolean is_member = FALSE;

102
    info_type = g_base_info_get_type (interface_info);
103 104 105 106

    if (info_type != GI_INFO_TYPE_UNION)
        return FALSE;

107
    union_info = (GIUnionInfo *) interface_info;
108 109 110 111 112 113 114 115 116 117 118
    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) {
119
            GIInterfaceInfo *field_iface_info;
120 121
            PyObject *py_type;

122 123
            field_iface_info = g_type_info_get_interface (field_type_info);
            py_type = _pygi_type_import_by_gi_info ((GIBaseInfo *) field_iface_info);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

            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;
}

143
gboolean
144 145 146 147
_pygi_marshal_from_py_gerror (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
148 149
                              GIArgument        *arg,
                              gpointer          *cleanup_data)
150
{
151 152
    PyErr_Format (PyExc_NotImplementedError,
                  "Marshalling for GErrors is not implemented");
153 154 155
    return FALSE;
}

156 157 158 159 160 161 162 163 164
/* _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) {
}

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
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);
191
        GIBaseInfo* glib_destroy_notify;
192 193 194

        g_assert (destroy_notify);

195
        glib_destroy_notify = g_irepository_find_by_name (NULL, "GLib", "DestroyNotify");
196 197 198 199 200 201 202 203 204 205 206 207 208 209
        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;
}

210
gboolean
211 212 213 214
_pygi_marshal_from_py_interface_callback (PyGIInvokeState   *state,
                                          PyGICallableCache *callable_cache,
                                          PyGIArgCache      *arg_cache,
                                          PyObject          *py_arg,
215 216
                                          GIArgument        *arg,
                                          gpointer          *cleanup_data)
217 218 219 220 221 222 223 224 225 226 227
{
    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) {
228
        user_data_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->user_data_index);
229
        if (user_data_cache->py_arg_index < state->n_py_in_args) {
230
            /* py_user_data is a borrowed reference. */
231
            py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
232 233
            if (!py_user_data)
                return FALSE;
234 235 236
            /* NULL out user_data if it was not supplied and the default arg placeholder
             * was used instead.
             */
237
            if (py_user_data == _PyGIDefaultArgPlaceholder) {
238
                py_user_data = NULL;
239 240 241 242 243 244 245 246 247 248 249
            } else if (callable_cache->user_data_varargs_index < 0) {
                /* For non-variable length user data, place the user data in a
                 * single item tuple which is concatenated to the callbacks arguments.
                 * This allows callback input arg marshaling to always expect a
                 * tuple for user data. Note the
                 */
                py_user_data = Py_BuildValue("(O)", py_user_data, NULL);
            } else {
                /* increment the ref borrowed from PyTuple_GetItem above */
                Py_INCREF (py_user_data);
            }
250 251 252 253 254 255 256
        }
    }

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

257 258 259 260
    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);
261 262 263 264 265 266 267 268

        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;
269

270 271 272
    /* always decref the user data as _pygi_make_native_closure adds its own ref */
    Py_XDECREF (py_user_data);

273 274 275
    /* 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.
     */
276 277 278 279
    if (user_data_cache != NULL) {
        state->in_args[user_data_cache->c_arg_index].v_pointer = closure;
    }

280 281 282 283 284 285 286 287
    /* 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) {
288
        destroy_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->destroy_notify_index);
289 290
    }

291
    if (destroy_cache) {
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        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;
        }
308 309
    }

310 311
    /* Use the PyGIClosure as data passed to cleanup for GI_SCOPE_TYPE_CALL. */
    *cleanup_data = closure;
312

313 314 315 316
    return TRUE;
}

gboolean
317 318 319 320
_pygi_marshal_from_py_interface_enum (PyGIInvokeState   *state,
                                      PyGICallableCache *callable_cache,
                                      PyGIArgCache      *arg_cache,
                                      PyObject          *py_arg,
321 322
                                      GIArgument        *arg,
                                      gpointer          *cleanup_data)
323
{
David Malcolm's avatar
David Malcolm committed
324 325
    PyObject *py_long;
    long c_long;
326 327
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
328
    GIBaseInfo *interface = NULL;
329

330
    is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
331

David Malcolm's avatar
David Malcolm committed
332 333
    py_long = PYGLIB_PyNumber_Long (py_arg);
    if (py_long == NULL) {
334 335 336 337
        PyErr_Clear();
        goto err;
    }

David Malcolm's avatar
David Malcolm committed
338 339 340 341 342 343 344 345 346 347
    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();
348
          g_base_info_unref (interface);
David Malcolm's avatar
David Malcolm committed
349 350
          return FALSE;
    }
351 352 353 354 355 356 357 358

    /* 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;

359
        for (i = 0; i < g_enum_info_get_n_values (iface_cache->interface_info); i++) {
360
            GIValueInfo *value_info =
361 362 363
                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
364
            if (c_long == enum_value) {
365 366 367 368 369 370 371 372 373
                is_found = TRUE;
                break;
            }
        }

        if (!is_found)
            goto err;
    }

374
    g_base_info_unref (interface);
375 376 377
    return TRUE;

err:
378 379
    if (interface)
        g_base_info_unref (interface);
380 381
    PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
                  iface_cache->type_name, py_arg->ob_type->tp_name);
382 383 384 385
    return FALSE;
}

gboolean
386 387 388 389
_pygi_marshal_from_py_interface_flags (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
390 391
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
392
{
David Malcolm's avatar
David Malcolm committed
393 394
    PyObject *py_long;
    long c_long;
395 396
    gint is_instance;
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;
David Malcolm's avatar
David Malcolm committed
397
    GIBaseInfo *interface;
398

399
    is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type);
400

David Malcolm's avatar
David Malcolm committed
401 402
    py_long = PYGLIB_PyNumber_Long (py_arg);
    if (py_long == NULL) {
403
        PyErr_Clear ();
404 405 406
        goto err;
    }

David Malcolm's avatar
David Malcolm committed
407 408
    c_long = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);
409 410

    /* only 0 or argument of type Flag is allowed */
David Malcolm's avatar
David Malcolm committed
411
    if (!is_instance && c_long != 0)
412 413
        goto err;

David Malcolm's avatar
David Malcolm committed
414 415 416 417 418
    /* Write c_long into arg */
    interface = g_type_info_get_interface (arg_cache->type_info);
    g_assert (g_base_info_get_type (interface) == GI_INFO_TYPE_FLAGS);
    if (!gi_argument_from_c_long(arg, c_long,
                                 g_enum_info_get_storage_type ((GIEnumInfo *)interface))) {
419
        g_base_info_unref (interface);
David Malcolm's avatar
David Malcolm committed
420 421 422
        return FALSE;
    }

423
    g_base_info_unref (interface);
424 425 426 427 428 429 430 431 432 433
    return TRUE;

err:
    PyErr_Format (PyExc_TypeError, "Expected a %s, but got %s",
                  iface_cache->type_name, py_arg->ob_type->tp_name);
    return FALSE;

}

gboolean
434 435 436 437
_pygi_marshal_from_py_interface_struct_cache_adapter (PyGIInvokeState   *state,
                                                      PyGICallableCache *callable_cache,
                                                      PyGIArgCache      *arg_cache,
                                                      PyObject          *py_arg,
438 439
                                                      GIArgument        *arg,
                                                      gpointer          *cleanup_data)
440 441 442
{
    PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *)arg_cache;

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    gboolean res =  _pygi_marshal_from_py_interface_struct (py_arg,
                                                            arg,
                                                            arg_cache->arg_name,
                                                            iface_cache->interface_info,
                                                            iface_cache->g_type,
                                                            iface_cache->py_type,
                                                            arg_cache->transfer,
                                                            TRUE, /*copy_reference*/
                                                            iface_cache->is_foreign,
                                                            arg_cache->is_pointer);

    /* Assume struct marshaling is always a pointer and assign cleanup_data
     * here rather than passing it further down the chain.
     */
    *cleanup_data = arg->v_pointer;
    return res;
459 460 461
}

gboolean
462 463 464 465
_pygi_marshal_from_py_interface_boxed (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
466 467
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
468
{
469 470
    PyErr_Format (PyExc_NotImplementedError,
                  "Marshalling for this type is not implemented yet");
471 472 473 474
    return FALSE;
}

gboolean
475 476 477 478
_pygi_marshal_from_py_interface_object (PyGIInvokeState   *state,
                                        PyGICallableCache *callable_cache,
                                        PyGIArgCache      *arg_cache,
                                        PyObject          *py_arg,
479 480
                                        GIArgument        *arg,
                                        gpointer          *cleanup_data)
481
{
482 483
    gboolean res = FALSE;

484 485 486 487 488
    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

489
    if (!PyObject_IsInstance (py_arg, ( (PyGIInterfaceCache *)arg_cache)->py_type)) {
490 491
        PyObject *module = PyObject_GetAttrString(py_arg, "__module__");

492
        PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s",
493
                      arg_cache->arg_name ? arg_cache->arg_name : "self",
494
                      ( (PyGIInterfaceCache *)arg_cache)->type_name,
495 496
                      module ? PYGLIB_PyUnicode_AsString(module) : "",
                      module ? "." : "",
497 498 499
                      py_arg->ob_type->tp_name);
        if (module)
            Py_DECREF (module);
500 501 502
        return FALSE;
    }

503 504 505
    res = _pygi_marshal_from_py_gobject (py_arg, arg, arg_cache->transfer);
    *cleanup_data = arg->v_pointer;
    return res;
506 507 508
}

gboolean
509 510 511 512
_pygi_marshal_from_py_interface_union (PyGIInvokeState   *state,
                                       PyGICallableCache *callable_cache,
                                       PyGIArgCache      *arg_cache,
                                       PyObject          *py_arg,
513 514
                                       GIArgument        *arg,
                                       gpointer          *cleanup_data)
515 516 517 518 519 520
{
    PyErr_Format(PyExc_NotImplementedError,
                 "Marshalling for this type is not implemented yet");
    return FALSE;
}

521
/* _pygi_marshal_from_py_gobject:
522 523 524
 * py_arg: (in):
 * arg: (out):
 */
525
gboolean
526 527 528
_pygi_marshal_from_py_gobject (PyObject *py_arg, /*in*/
                               GIArgument *arg,  /*out*/
                               GITransfer transfer) {
529 530
    GObject *gobj;

531
    if (py_arg == Py_None) {
532 533 534 535
        arg->v_pointer = NULL;
        return TRUE;
    }

536 537 538 539 540 541 542 543
    if (!pygobject_check (py_arg, &PyGObject_Type)) {
        PyObject *repr = PyObject_Repr (py_arg);
        PyErr_Format(PyExc_TypeError, "expected GObject but got %s",
                     PYGLIB_PyUnicode_AsString (repr));
        Py_DECREF (repr);
        return FALSE;
    }

544
    gobj = pygobject_get (py_arg);
545
    if (transfer == GI_TRANSFER_EVERYTHING) {
546 547
        /* For transfer everything, add a new ref that the callee will take ownership of.
         * Pythons existing ref to the GObject will be managed with the PyGObject wrapper.
548 549
         */
        g_object_ref (gobj);
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    }

    arg->v_pointer = gobj;
    return TRUE;
}

/* _pygi_marshal_from_py_gobject_out_arg:
 * py_arg: (in):
 * arg: (out):
 *
 * A specialization for marshaling Python GObjects used for out/return values
 * from a Python implemented vfuncs, signals, or an assignment to a GObject property.
 */
gboolean
_pygi_marshal_from_py_gobject_out_arg (PyObject *py_arg, /*in*/
                                       GIArgument *arg,  /*out*/
                                       GITransfer transfer) {
    GObject *gobj;
    if (!_pygi_marshal_from_py_gobject (py_arg, arg, transfer)) {
        return FALSE;
    }
571

572 573 574 575 576 577
    /* HACK: At this point the basic marshaling of the GObject was successful
     * but we add some special case hacks for vfunc returns due to buggy APIs:
     * https://bugzilla.gnome.org/show_bug.cgi?id=693393
     */
    gobj = arg->v_pointer;
    if (py_arg->ob_refcnt == 1 && gobj->ref_count == 1) {
578 579 580 581 582 583 584
        /* If both object ref counts are only 1 at this point (the reference held
         * in a return tuple), we assume the GObject will be free'd before reaching
         * its target and become invalid. So instead of getting invalid object errors
         * we add a new GObject ref.
         */
        g_object_ref (gobj);

585
        if (((PyGObject *)py_arg)->private_flags.flags & PYGOBJECT_GOBJECT_WAS_FLOATING) {
586
            /*
587 588 589 590 591 592 593
             * We want to re-float instances that were floating and the Python
             * wrapper assumed ownership. With the additional caveat that there
             * are not any strong references beyond the return tuple.
             */
            g_object_force_floating (gobj);

        } else {
594
            PyObject *repr = PyObject_Repr (py_arg);
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
            gchar *msg = g_strdup_printf ("Expecting to marshal a borrowed reference for %s, "
                                          "but nothing in Python is holding a reference to this object. "
                                          "See: https://bugzilla.gnome.org/show_bug.cgi?id=687522",
                                          PYGLIB_PyUnicode_AsString(repr));
            Py_DECREF (repr);
            if (PyErr_WarnEx (PyExc_RuntimeWarning, msg, 2)) {
                g_free (msg);
                return FALSE;
            }
            g_free (msg);
        }
    }

    return TRUE;
}
610

611
/* _pygi_marshal_from_py_gvalue:
612 613 614
 * py_arg: (in):
 * arg: (out):
 * transfer:
615 616
 * copy_reference: TRUE if arg should use the pointer reference held by py_arg
 *                 when it is already holding a GValue vs. copying the value.
617 618
 */
gboolean
619 620 621 622
_pygi_marshal_from_py_gvalue (PyObject *py_arg,
                              GIArgument *arg,
                              GITransfer transfer,
                              gboolean copy_reference) {
623 624 625 626 627 628 629 630 631 632 633 634
    GValue *value;
    GType object_type;

    object_type = pyg_type_from_object_strict ( (PyObject *) py_arg->ob_type, FALSE);
    if (object_type == G_TYPE_INVALID) {
        PyErr_SetString (PyExc_RuntimeError, "unable to retrieve object's GType");
        return FALSE;
    }

    /* if already a gvalue, use that, else marshal into gvalue */
    if (object_type == G_TYPE_VALUE) {
        GValue *source_value = pyg_boxed_get (py_arg, GValue);
635 636 637 638
        if (copy_reference) {
            value = source_value;
        } else {
            value = g_slice_new0 (GValue);
639
            g_value_init (value, G_VALUE_TYPE (source_value));
640 641
            g_value_copy (source_value, value);
        }
642
    } else {
643 644
        value = g_slice_new0 (GValue);
        g_value_init (value, object_type);
645
        if (pyg_value_from_pyobject (value, py_arg) < 0) {
646
            g_slice_free (GValue, value);
647 648 649 650 651 652 653 654
            PyErr_SetString (PyExc_RuntimeError, "PyObject conversion to GValue failed");
            return FALSE;
        }
    }

    arg->v_pointer = value;
    return TRUE;
}
655

656
/* _pygi_marshal_from_py_gclosure:
657 658 659 660
 * py_arg: (in):
 * arg: (out):
 */
gboolean
661 662
_pygi_marshal_from_py_gclosure(PyObject *py_arg,
                               GIArgument *arg)
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
{
    GClosure *closure;
    GType object_gtype = pyg_type_from_object_strict (py_arg, FALSE);

    if ( !(PyCallable_Check(py_arg) ||
           g_type_is_a (object_gtype, G_TYPE_CLOSURE))) {
        PyErr_Format (PyExc_TypeError, "Must be callable, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    if (g_type_is_a (object_gtype, G_TYPE_CLOSURE))
        closure = (GClosure *)pyg_boxed_get (py_arg, void);
    else
        closure = pyg_closure_new (py_arg, NULL, NULL);

    if (closure == NULL) {
        PyErr_SetString (PyExc_RuntimeError, "PyObject conversion to GClosure failed");
        return FALSE;
    }

    arg->v_pointer = closure;
    return TRUE;
}
687 688

gboolean
689 690 691 692 693 694 695 696
_pygi_marshal_from_py_interface_struct (PyObject *py_arg,
                                        GIArgument *arg,
                                        const gchar *arg_name,
                                        GIBaseInfo *interface_info,
                                        GType g_type,
                                        PyObject *py_type,
                                        GITransfer transfer,
                                        gboolean copy_reference,
697 698
                                        gboolean is_foreign,
                                        gboolean is_pointer)
699
{
700 701
    gboolean is_union = FALSE;

702 703 704 705 706 707 708 709 710 711
    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    /* FIXME: handle this large if statement in the cache
     *        and set the correct marshaller
     */

    if (g_type_is_a (g_type, G_TYPE_CLOSURE)) {
712
        return _pygi_marshal_from_py_gclosure (py_arg, arg);
713
    } else if (g_type_is_a (g_type, G_TYPE_VALUE)) {
714 715 716 717
        return _pygi_marshal_from_py_gvalue(py_arg,
                                            arg,
                                            transfer,
                                            copy_reference);
718 719 720 721 722 723 724 725 726 727
    } else if (is_foreign) {
        PyObject *success;
        success = pygi_struct_foreign_convert_to_g_argument (py_arg,
                                                             interface_info,
                                                             transfer,
                                                             arg);

        return (success == Py_None);
    } else if (!PyObject_IsInstance (py_arg, py_type)) {
        /* first check to see if this is a member of the expected union */
728 729 730
        is_union = _is_union_member (interface_info, py_arg);
        if (!is_union) {
            goto type_error;
731 732 733 734
        }
    }

    if (g_type_is_a (g_type, G_TYPE_BOXED)) {
735 736 737 738
        /* Additionally use pyg_type_from_object to pull the stashed __gtype__
         * attribute off of the input argument for type checking. This is needed
         * to work around type discrepancies in cases with aliased (typedef) types.
         * e.g. GtkAllocation, GdkRectangle.
739 740
         * See: https://bugzilla.gnomethere are .org/show_bug.cgi?id=707140
         */
741 742
        if (is_union || pyg_boxed_check (py_arg, g_type) ||
                g_type_is_a (pyg_type_from_object (py_arg), g_type)) {
743 744 745 746 747
            arg->v_pointer = pyg_boxed_get (py_arg, void);
            if (transfer == GI_TRANSFER_EVERYTHING) {
                arg->v_pointer = g_boxed_copy (g_type, arg->v_pointer);
            }
        } else {
748
            goto type_error;
749 750 751 752 753
        }

    } else if (g_type_is_a (g_type, G_TYPE_POINTER) ||
               g_type_is_a (g_type, G_TYPE_VARIANT) ||
               g_type  == G_TYPE_NONE) {
754
        g_warn_if_fail (g_type_is_a (g_type, G_TYPE_VARIANT) || !is_pointer || transfer == GI_TRANSFER_NOTHING);
755 756 757 758 759 760 761

        if (g_type_is_a (g_type, G_TYPE_VARIANT) &&
                pyg_type_from_object (py_arg) != G_TYPE_VARIANT) {
            PyErr_SetString (PyExc_TypeError, "expected GLib.Variant");
            return FALSE;
        }
        arg->v_pointer = pyg_pointer_get (py_arg, void);
762 763 764
        if (transfer == GI_TRANSFER_EVERYTHING) {
            g_variant_ref ((GVariant *)arg->v_pointer);
        }
765 766 767 768 769 770 771 772

    } else {
        PyErr_Format (PyExc_NotImplementedError,
                      "structure type '%s' is not supported yet",
                      g_type_name(g_type));
        return FALSE;
    }
    return TRUE;
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789

type_error:
    {
        gchar *type_name = _pygi_g_base_info_get_fullname (interface_info);
        PyObject *module = PyObject_GetAttrString(py_arg, "__module__");

        PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s",
                      arg_name ? arg_name : "self",
                      type_name,
                      module ? PYGLIB_PyUnicode_AsString(module) : "",
                      module ? "." : "",
                      py_arg->ob_type->tp_name);
        if (module)
            Py_DECREF (module);
        g_free (type_name);
        return FALSE;
    }
790
}