Exemplo n.º 1
0
/**
 * pyg_value_from_pyobject:
 * @value: the GValue object to store the converted value in.
 * @obj: the Python object to convert.
 *
 * This function converts a Python object and stores the result in a
 * GValue.  The GValue must be initialised in advance with
 * g_value_init().  If the Python object can't be converted to the
 * type of the GValue, then an error is returned.
 *
 * Returns: 0 on success, -1 on error.
 */
int
pyg_value_from_pyobject(GValue *value, PyObject *obj)
{
    PyObject *tmp;

    switch (G_TYPE_FUNDAMENTAL(G_VALUE_TYPE(value))) {
    case G_TYPE_INTERFACE:
	/* we only handle interface types that have a GObject prereq */
	if (g_type_is_a(G_VALUE_TYPE(value), G_TYPE_OBJECT)) {
	    if (obj == Py_None)
		g_value_set_object(value, NULL);
	    else {
		if (!PyObject_TypeCheck(obj, &PyGObject_Type)) {
		    return -1;
		}
		if (!G_TYPE_CHECK_INSTANCE_TYPE(pygobject_get(obj),
						G_VALUE_TYPE(value))) {
		    return -1;
		}
		g_value_set_object(value, pygobject_get(obj));
	    }
	} else {
	    return -1;
	}
	break;
    case G_TYPE_CHAR:
#if PY_VERSION_HEX < 0x03000000
	if (PyString_Check(obj)) {
	    g_value_set_char(value, PyString_AsString(obj)[0]);
	} else
#endif
	if (PyUnicode_Check(obj)) {
	    tmp = PyUnicode_AsUTF8String(obj);
	    g_value_set_char(value, PYGLIB_PyBytes_AsString(tmp)[0]);
	    Py_DECREF(tmp);
	} else {
	    PyErr_Clear();
	    return -1;
	}

	break;
    case G_TYPE_UCHAR:
	if (PYGLIB_PyLong_Check(obj)) {
	    glong val;
	    val = PYGLIB_PyLong_AsLong(obj);
	    if (val >= 0 && val <= 255)
	      g_value_set_uchar(value, (guchar)PYGLIB_PyLong_AsLong (obj));
	    else
	      return -1;
#if PY_VERSION_HEX < 0x03000000
	} else if (PyString_Check(obj)) {
	    g_value_set_uchar(value, PyString_AsString(obj)[0]);
#endif
	} else if (PyUnicode_Check(obj)) {
	    tmp = PyUnicode_AsUTF8String(obj);
	    g_value_set_uchar(value, PYGLIB_PyBytes_AsString(tmp)[0]);
	    Py_DECREF(tmp);
	} else {
	    PyErr_Clear();
	    return -1;
	}
	break;
    case G_TYPE_BOOLEAN:
	g_value_set_boolean(value, PyObject_IsTrue(obj));
	break;
    case G_TYPE_INT:
	g_value_set_int(value, PYGLIB_PyLong_AsLong(obj));
	break;
    case G_TYPE_UINT:
	{
	    if (PYGLIB_PyLong_Check(obj)) {
		glong val;

		val = PYGLIB_PyLong_AsLong(obj);
		if (val >= 0 && val <= G_MAXUINT)
		    g_value_set_uint(value, (guint)val);
		else
		    return -1;
	    } else {
		g_value_set_uint(value, PyLong_AsUnsignedLong(obj));
	    }
	}
	break;
    case G_TYPE_LONG:
	g_value_set_long(value, PYGLIB_PyLong_AsLong(obj));
	break;
    case G_TYPE_ULONG:
#if PY_VERSION_HEX < 0x03000000
	if (PyInt_Check(obj)) {
            long val;

            val = PYGLIB_PyLong_AsLong(obj);
            if (val < 0) {
                PyErr_SetString(PyExc_OverflowError, "negative value not allowed for uint64 property");
                return -1;
            }
            g_value_set_ulong(value, (gulong)val);
        } else
#endif
        if (PyLong_Check(obj))
	    g_value_set_ulong(value, PyLong_AsUnsignedLong(obj));
        else
            return -1;
        break;
    case G_TYPE_INT64:
	g_value_set_int64(value, PyLong_AsLongLong(obj));
	break;
    case G_TYPE_UINT64:
#if PY_VERSION_HEX < 0x03000000
        if (PyInt_Check(obj)) {
            long v = PyInt_AsLong(obj);
            if (v < 0) {
                PyErr_SetString(PyExc_OverflowError, "negative value not allowed for uint64 property");
                return -1;
            }
            g_value_set_uint64(value, v);
        } else
#endif
        if (PyLong_Check(obj))
            g_value_set_uint64(value, PyLong_AsUnsignedLongLong(obj));
        else
            return -1;
	break;
    case G_TYPE_ENUM:
	{
	    gint val = 0;
	    if (pyg_enum_get_value(G_VALUE_TYPE(value), obj, &val) < 0) {
		PyErr_Clear();
		return -1;
	    }
	    g_value_set_enum(value, val);
	}
	break;
    case G_TYPE_FLAGS:
	{
	    gint val = 0;
	    if (pyg_flags_get_value(G_VALUE_TYPE(value), obj, &val) < 0) {
		PyErr_Clear();
		return -1;
	    }
	    g_value_set_flags(value, val);
	}
	break;
    case G_TYPE_FLOAT:
	g_value_set_float(value, PyFloat_AsDouble(obj));
	break;
    case G_TYPE_DOUBLE:
	g_value_set_double(value, PyFloat_AsDouble(obj));
	break;
    case G_TYPE_STRING:
	if (obj == Py_None) {
	    g_value_set_string(value, NULL);
#if PY_VERSION_HEX < 0x03000000
	} else if (PyString_Check(obj)) {
	    g_value_set_string(value, PyString_AsString(obj));
#endif
	} else if (PyUnicode_Check(obj)) {
	    tmp = PyUnicode_AsUTF8String(obj);
	    g_value_set_string(value, PYGLIB_PyBytes_AsString(tmp));
	    Py_DECREF(tmp);
	} else {
	    PyErr_Clear();
	    return -1;
	}
	break;
    case G_TYPE_POINTER:
	if (obj == Py_None)
	    g_value_set_pointer(value, NULL);
	else if (PyObject_TypeCheck(obj, &PyGPointer_Type) &&
		   G_VALUE_HOLDS(value, ((PyGPointer *)obj)->gtype))
	    g_value_set_pointer(value, pyg_pointer_get(obj, gpointer));
	else if (PYGLIB_CPointer_Check(obj))
	    g_value_set_pointer(value, PYGLIB_CPointer_GetPointer(obj, NULL));
	else
	    return -1;
	break;
    case G_TYPE_BOXED: {
	PyGTypeMarshal *bm;

	if (obj == Py_None)
	    g_value_set_boxed(value, NULL);
	else if (G_VALUE_HOLDS(value, PY_TYPE_OBJECT))
	    g_value_set_boxed(value, obj);
	else if (PyObject_TypeCheck(obj, &PyGBoxed_Type) &&
		   G_VALUE_HOLDS(value, ((PyGBoxed *)obj)->gtype))
	    g_value_set_boxed(value, pyg_boxed_get(obj, gpointer));
        else if (G_VALUE_HOLDS(value, G_TYPE_VALUE)) {
            GType type;
            GValue *n_value;

            type = pyg_type_from_object((PyObject*)Py_TYPE(obj));
            if (G_UNLIKELY (! type)) {
                PyErr_Clear();
                return -1;
            }
            n_value = g_new0 (GValue, 1);
            g_value_init (n_value, type);
            g_value_take_boxed (value, n_value);
            return pyg_value_from_pyobject (n_value, obj);
        }
        else if (PySequence_Check(obj) &&
		   G_VALUE_HOLDS(value, G_TYPE_VALUE_ARRAY))
	    return pyg_value_array_from_pyobject(value, obj, NULL);
	else if (PYGLIB_PyUnicode_Check(obj) &&
                 G_VALUE_HOLDS(value, G_TYPE_GSTRING)) {
            GString *string;
            char *buffer;
            Py_ssize_t len;
            if (PYGLIB_PyUnicode_AsStringAndSize(obj, &buffer, &len))
                return -1;
            string = g_string_new_len(buffer, len);
	    g_value_set_boxed(value, string);
	    g_string_free (string, TRUE);
            break;
        }
	else if ((bm = pyg_type_lookup(G_VALUE_TYPE(value))) != NULL)
	    return bm->tovalue(value, obj);
	else if (PYGLIB_CPointer_Check(obj))
	    g_value_set_boxed(value, PYGLIB_CPointer_GetPointer(obj, NULL));
	else
	    return -1;
	break;
    }
    case G_TYPE_PARAM:
	if (PyGParamSpec_Check(obj))
	    g_value_set_param(value, PYGLIB_CPointer_GetPointer(obj, NULL));
	else
	    return -1;
	break;
    case G_TYPE_OBJECT:
	if (obj == Py_None) {
	    g_value_set_object(value, NULL);
	} else if (PyObject_TypeCheck(obj, &PyGObject_Type) &&
		   G_TYPE_CHECK_INSTANCE_TYPE(pygobject_get(obj),
					      G_VALUE_TYPE(value))) {
	    g_value_set_object(value, pygobject_get(obj));
	} else
	    return -1;
	break;
    default:
	{
	    PyGTypeMarshal *bm;
	    if ((bm = pyg_type_lookup(G_VALUE_TYPE(value))) != NULL)
		return bm->tovalue(value, obj);
	    break;
	}
    }
    if (PyErr_Occurred()) {
        g_value_unset(value);
        PyErr_Clear();
        return -1;
    }
    return 0;
}
Exemplo n.º 2
0
PyObject* ItemSupplier::create(PyTypeObject* pytype, PyObject* args, PyObject* kwds)
{
  try
  {
    // Pick up the supplier
    PyObject* sup = PyDict_GetItemString(kwds,"supplier");
    if (!sup)
      throw DataException("missing supplier on ItemSupplier");
    if (!PyObject_TypeCheck(sup, Supplier::metadata->pythonClass))
      throw DataException("ItemSupplier supplier must be of type supplier");

    // Pick up the item
    PyObject* it = PyDict_GetItemString(kwds,"item");
    if (!it)
      throw DataException("missing item on ItemSupplier");
    if (!PyObject_TypeCheck(it, Item::metadata->pythonClass))
      throw DataException("ItemSupplier item must be of type item");

    // Pick up the priority
    PyObject* q1 = PyDict_GetItemString(kwds,"priority");
    int q2 = q1 ? PythonData(q1).getInt() : 1;

    // Pick up the effective dates
    DateRange eff;
    PyObject* eff_start = PyDict_GetItemString(kwds,"effective_start");
    if (eff_start)
    {
      PythonData d(eff_start);
      eff.setStart(d.getDate());
    }
    PyObject* eff_end = PyDict_GetItemString(kwds,"effective_end");
    if (eff_end)
    {
      PythonData d(eff_end);
      eff.setEnd(d.getDate());
    }

    // Create the ItemSupplier
    ItemSupplier *l = new ItemSupplier(
      static_cast<Supplier*>(sup),
      static_cast<Item*>(it),
      q2, eff
    );

    // Iterate over extra keywords, and set attributes.   @todo move this responsibility to the readers...
    if (l)
    {
      PyObject *key, *value;
      Py_ssize_t pos = 0;
      while (PyDict_Next(kwds, &pos, &key, &value))
      {
        PythonData field(value);
        PyObject* key_utf8 = PyUnicode_AsUTF8String(key);
        DataKeyword attr(PyBytes_AsString(key_utf8));
        Py_DECREF(key_utf8);
        if (!attr.isA(Tags::effective_end) && !attr.isA(Tags::effective_start)
          && !attr.isA(Tags::supplier) && !attr.isA(Tags::item)
          && !attr.isA(Tags::type) && !attr.isA(Tags::action))
        {
          const MetaFieldBase* fmeta = l->getType().findField(attr.getHash());
          if (!fmeta && l->getType().category)
            fmeta = l->getType().category->findField(attr.getHash());
          if (fmeta)
            // Update the attribute
            fmeta->setField(l, field);
          else
            l->setProperty(attr.getName(), value);
        }
      };
    }

    // Return the object
    Py_INCREF(l);
    return static_cast<PyObject*>(l);
  }
  catch (...)
  {
    PythonType::evalException();
    return NULL;
  }
}
Exemplo n.º 3
0
// Convert a Python object to a QJSValue.
int qpyqml_convertTo_QJSValue(PyObject *py, PyObject *transferObj,
        QJSValue **cpp, int *isErr)
{
    if (PyObject_TypeCheck(py, sipTypeAsPyTypeObject(sipType_QJSValue_SpecialValue)))
    {
        *cpp = new QJSValue((QJSValue::SpecialValue)SIPLong_AsLong(py));

        return sipGetState(transferObj);
    }

    if (PyBool_Check(py))
    {
        *cpp = new QJSValue(py == Py_True);

        return sipGetState(transferObj);
    }

#if PY_MAJOR_VERSION >= 3
    if (PyLong_Check(py))
    {
        *cpp = new QJSValue((int)PyLong_AS_LONG(py));

        return sipGetState(transferObj);
    }
#else
    if (PyInt_Check(py))
    {
        *cpp = new QJSValue((int)PyInt_AS_LONG(py));

        return sipGetState(transferObj);
    }
#endif

    if (PyFloat_Check(py))
    {
        *cpp = new QJSValue((double)PyFloat_AS_DOUBLE(py));

        return sipGetState(transferObj);
    }

    if (sipCanConvertToType(py, sipType_QString, 0))
    {
        int state;
        QString *qs = reinterpret_cast<QString *>(sipConvertToType(py,
                sipType_QString, 0, 0, &state, isErr));

        if (*isErr)
        {
            sipReleaseType(qs, sipType_QString, state);
            return 0;
        }

        *cpp = new QJSValue(*qs);

        sipReleaseType(qs, sipType_QString, state);

        return sipGetState(transferObj);
    }

    *cpp = reinterpret_cast<QJSValue *>(sipConvertToType(py, sipType_QJSValue,
            transferObj, SIP_NO_CONVERTORS, 0, isErr));

    return 0;
}
Exemplo n.º 4
0
PyObject* OperatorDelete::solve(PyObject *self, PyObject *args)
{
    // Parse the argument
    PyObject *obj = nullptr;
    short objtype = 0;
    if (args && !PyArg_ParseTuple(args, "|O:solve", &obj)) return nullptr;
    if (obj)
    {
        if (PyObject_TypeCheck(obj, Demand::metadata->pythonClass))
            objtype = 1;
        else if (PyObject_TypeCheck(obj, Buffer::metadata->pythonClass))
            objtype = 2;
        else if (PyObject_TypeCheck(obj, Resource::metadata->pythonClass))
            objtype = 3;
        else if (PyObject_TypeCheck(obj, OperationPlan::metadata->pythonClass))
            objtype = 4;
        else
        {
            PyErr_SetString(
                PythonDataException,
                "solve(d) argument must be a demand, buffer, resource or operationplan"
            );
            return nullptr;
        }
    }

    Py_BEGIN_ALLOW_THREADS   // Free Python interpreter for other threads
    try
    {
        OperatorDelete* sol = static_cast<OperatorDelete*>(self);
        switch (objtype)
        {
        case 0:
            // Delete all excess
            sol->solve();
            break;
        case 1:
            // Delete upstream of a single demand
            sol->solve(static_cast<Demand*>(obj));
            break;
        case 2:
            // Delete upstream of a single buffer
            sol->solve(static_cast<Buffer*>(obj));
            break;
        case 3:
            // Delete upstream of a single resource
            sol->solve(static_cast<Resource*>(obj));
        case 4:
            // Delete an operationplan
            sol->solve(static_cast<OperationPlan*>(obj));
        }
    }
    catch(...)
    {
        Py_BLOCK_THREADS;
        PythonType::evalException();
        return nullptr;
    }
    Py_END_ALLOW_THREADS   // Reclaim Python interpreter
    return Py_BuildValue("");
}
Exemplo n.º 5
0
static int
Wcs_init(
    Wcs* self,
    PyObject* args,
    /*@[email protected]*/ PyObject* kwds) {

  size_t       i;
  PyObject*    py_sip;
  PyObject*    py_wcsprm;
  PyObject*    py_distortion_lookup[2];
  PyObject*    py_det2im[2];

  if (!PyArg_ParseTuple
      (args, "O(OO)O(OO):Wcs.__init__",
       &py_sip,
       &py_distortion_lookup[0],
       &py_distortion_lookup[1],
       &py_wcsprm,
       &py_det2im[0],
       &py_det2im[1])) {
    return -1;
  }

  /* Check and set Distortion lookup tables */
  for (i = 0; i < 2; ++i) {
    if (py_det2im[i] != NULL && py_det2im[i] != Py_None) {
      if (!PyObject_TypeCheck(py_det2im[i], &PyDistLookupType)) {
        PyErr_SetString(PyExc_TypeError,
                        "Arg 4 must be a pair of DistortionLookupTable or None objects");
        return -1;
      }

      self->py_det2im[i] = py_det2im[i];
      self->x.det2im[i] = &(((PyDistLookup*)py_det2im[i])->x);
    }
  }

  /* Check and set SIP */
  if (py_sip != NULL && py_sip != Py_None) {
    if (!PyObject_TypeCheck(py_sip, &PySipType)) {
      PyErr_SetString(PyExc_TypeError,
                      "Arg 1 must be Sip object");
      return -1;
    }

    self->py_sip = py_sip;
    self->x.sip = &(((PySip*)py_sip)->x);
  }

  /* Check and set Distortion lookup tables */
  for (i = 0; i < 2; ++i) {
    if (py_distortion_lookup[i] != NULL && py_distortion_lookup[i] != Py_None) {
      if (!PyObject_TypeCheck(py_distortion_lookup[i], &PyDistLookupType)) {
        PyErr_SetString(PyExc_TypeError,
                        "Arg 2 must be a pair of DistortionLookupTable or None objects");
        return -1;
      }

      self->py_distortion_lookup[i] = py_distortion_lookup[i];
      self->x.cpdis[i] = &(((PyDistLookup*)py_distortion_lookup[i])->x);
    }
  }

  /* Set and lookup Wcsprm object */
  if (py_wcsprm != NULL && py_wcsprm != Py_None) {
    if (!PyObject_TypeCheck(py_wcsprm, &PyWcsprmType)) {
      PyErr_SetString(PyExc_TypeError,
                      "Arg 3 must be Wcsprm object");
      return -1;
    }

    self->py_wcsprm = py_wcsprm;
    self->x.wcs = &(((PyWcsprm*)py_wcsprm)->x);
  }

  Py_XINCREF(self->py_sip);
  Py_XINCREF(self->py_distortion_lookup[0]);
  Py_XINCREF(self->py_distortion_lookup[1]);
  Py_XINCREF(self->py_wcsprm);
  Py_XINCREF(self->py_det2im[0]);
  Py_XINCREF(self->py_det2im[1]);

  return 0;
}
Exemplo n.º 6
0
_PUBLIC_ int pytalloc_BaseObject_check(PyObject *obj)
{
	PyTypeObject *tp = pytalloc_GetBaseObjectType();

	return PyObject_TypeCheck(obj, tp);
}
Exemplo n.º 7
0
static int
dialect_init(DialectObj * self, PyObject * args, PyObject * kwargs)
{
        PyObject *dialect = NULL, *name_obj, *value_obj;

	self->quotechar = '"';
	self->delimiter = ',';
	self->escapechar = '\0';
	self->skipinitialspace = 0;
        Py_XDECREF(self->lineterminator);
	self->lineterminator = PyString_FromString("\r\n");
        if (self->lineterminator == NULL)
                return -1;
	self->quoting = QUOTE_MINIMAL;
	self->doublequote = 1;
	self->strict = 0;

	if (!PyArg_UnpackTuple(args, "", 0, 1, &dialect))
                return -1;
        Py_XINCREF(dialect);
        if (kwargs != NULL) {
                PyObject * key = PyString_FromString("dialect");
                PyObject * d;

                d = PyDict_GetItem(kwargs, key);
                if (d) {
                        Py_INCREF(d);
                        Py_XDECREF(dialect);
                        PyDict_DelItem(kwargs, key);
                        dialect = d;
                }
                Py_DECREF(key);
        }
        if (dialect != NULL) {
                int i;
                PyObject * dir_list;

                /* If dialect is a string, look it up in our registry */
                if (PyString_Check(dialect)
#ifdef Py_USING_UNICODE
		    || PyUnicode_Check(dialect)
#endif
			) {
                        PyObject * new_dia;
                        new_dia = get_dialect_from_registry(dialect);
                        Py_DECREF(dialect);
                        if (new_dia == NULL)
                                return -1;
                        dialect = new_dia;
                }
                /* A class rather than an instance? Instantiate */
                if (PyObject_TypeCheck(dialect, &PyClass_Type)) {
                        PyObject * new_dia;
                        new_dia = PyObject_CallFunction(dialect, "");
                        Py_DECREF(dialect);
                        if (new_dia == NULL)
                                return -1;
                        dialect = new_dia;
                }
                /* Make sure we finally have an instance */
                if (!PyInstance_Check(dialect) ||
                    (dir_list = PyObject_Dir(dialect)) == NULL) {
                        PyErr_SetString(PyExc_TypeError,
                                        "dialect must be an instance");
                        Py_DECREF(dialect);
                        return -1;
                }
                /* And extract the attributes */
                for (i = 0; i < PyList_GET_SIZE(dir_list); ++i) {
			char *s;
                        name_obj = PyList_GET_ITEM(dir_list, i);
			s = PyString_AsString(name_obj);
			if (s == NULL)
				return -1;
                        if (s[0] == '_')
                                continue;
                        value_obj = PyObject_GetAttr(dialect, name_obj);
                        if (value_obj) {
                                if (PyObject_SetAttr((PyObject *)self, 
                                                     name_obj, value_obj)) {
					Py_DECREF(value_obj);
                                        Py_DECREF(dir_list);
					Py_DECREF(dialect);
                                        return -1;
                                }
                                Py_DECREF(value_obj);
                        }
                }
                Py_DECREF(dir_list);
                Py_DECREF(dialect);
        }
        if (kwargs != NULL) {
                int pos = 0;

                while (PyDict_Next(kwargs, &pos, &name_obj, &value_obj)) {
                        if (PyObject_SetAttr((PyObject *)self, 
                                             name_obj, value_obj))
                                return -1;
                }
        }
        return 0;
}
Exemplo n.º 8
0
//
// checks to see if the python object is a storage list
int PyStorageList_Check(PyObject *value) {
  return PyObject_TypeCheck(value, &PyStorageList_Type);
}
Exemplo n.º 9
0
int DyND_PyWrapper_Check(PyObject *obj)
{
  return PyObject_TypeCheck(obj, DyND_PyWrapper_Type<T>());
}
Exemplo n.º 10
0
/*
 * Checks if the object is a pyjiterator.
 */
int pyjiterator_check(PyObject *obj) {
    if(PyObject_TypeCheck(obj, &PyJiterator_Type))
        return 1;
    return 0;
}
Exemplo n.º 11
0
//-------------------------------------------------------------------------------------
PyObject* VectorDescription::onSetValue(PyObject* parentObj, PyObject* value)
{
	switch(elemCount_)
	{
	case 2:
		{
			if(PyObject_TypeCheck(value, script::ScriptVector2::getScriptType()))
			{
				return PropertyDescription::onSetValue(parentObj, value);
			}
			else
			{
				PyObject* pyobj = PyObject_GetAttrString(parentObj, const_cast<char*>(getName()));
				if(pyobj == NULL)
					return NULL;

				script::ScriptVector2* v = static_cast<script::ScriptVector2*>(pyobj);
				v->__py_pySet(v, value);
				Py_XDECREF(pyobj);
				return v;
			}
		}
		break;
	case 3:
		{
			if(PyObject_TypeCheck(value, script::ScriptVector3::getScriptType()))
			{
				return PropertyDescription::onSetValue(parentObj, value);
			}
			else
			{
				PyObject* pyobj = PyObject_GetAttrString(parentObj, const_cast<char*>(getName()));
				if(pyobj == NULL)
					return NULL;

				script::ScriptVector3* v = static_cast<script::ScriptVector3*>(pyobj);
				v->__py_pySet(v, value);
				Py_XDECREF(pyobj);
				return v;
			}
		}
		break;
	case 4:
		{
			if(PyObject_TypeCheck(value, script::ScriptVector4::getScriptType()))
			{
				return PropertyDescription::onSetValue(parentObj, value);
			}
			else
			{
				PyObject* pyobj = PyObject_GetAttrString(parentObj, const_cast<char*>(getName()));
				if(pyobj == NULL)
					return NULL;

				script::ScriptVector4* v = static_cast<script::ScriptVector4*>(pyobj);
				v->__py_pySet(v, value);
				Py_XDECREF(pyobj);
				return v;
			}
		}
		break;
	};
	
	return NULL;	
}
Exemplo n.º 12
0
static PyObject *
pyg_enum_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = { "value", NULL };
    long value;
    PyObject *pytc, *values, *ret, *intvalue;
    GType gtype;
    GEnumClass *eclass;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "l", kwlist, &value))
	return NULL;

    pytc = PyObject_GetAttrString((PyObject *)type, "__gtype__");
    if (!pytc)
	return NULL;

    if (!PyObject_TypeCheck(pytc, &PyGTypeWrapper_Type)) {
	Py_DECREF(pytc);
	PyErr_SetString(PyExc_TypeError,
			"__gtype__ attribute not a typecode");
	return NULL;
    }

    gtype = pyg_type_from_object(pytc);
    Py_DECREF(pytc);

    eclass = G_ENUM_CLASS(g_type_class_ref(gtype));

    /* A check that 0 < value < eclass->n_values was here but got
     * removed: enumeration values do not need to be consequitive,
     * e.g. GtkPathPriorityType values are not.
     */

    values = PyObject_GetAttrString((PyObject *)type, "__enum_values__");
    if (!values) {
	g_type_class_unref(eclass);
	return NULL;
    }

    /* Note that size of __enum_values__ dictionary can easily be less
     * than 'n_values'.  This happens if some values of the enum are
     * numerically equal, e.g. gtk.ANCHOR_N == gtk.ANCHOR_NORTH.
     * Johan said that "In retrospect, using a dictionary to store the
     * values might not have been that good", but we need to keep
     * backward compatibility.
     */
    if (!PyDict_Check(values) || PyDict_Size(values) > eclass->n_values) {
	PyErr_SetString(PyExc_TypeError, "__enum_values__ badly formed");
	Py_DECREF(values);
	g_type_class_unref(eclass);
	return NULL;
    }

    g_type_class_unref(eclass);

    intvalue = PYGLIB_PyLong_FromLong(value);
    ret = PyDict_GetItem(values, intvalue);
    Py_DECREF(intvalue);
    Py_DECREF(values);
    if (ret)
        Py_INCREF(ret);
    else
	PyErr_Format(PyExc_ValueError, "invalid enum value: %ld", value);

    return ret;
}
Exemplo n.º 13
0
bool PythonQtDebugAPI::isPythonQtClassWrapper( PyObject* object )
{
  return PyObject_TypeCheck(object, &PythonQtClassWrapper_Type) != 0;
}
Exemplo n.º 14
0
int pyjobject_check(PyObject *obj) {
    if(PyObject_TypeCheck(obj, &PyJobject_Type))
        return 1;
    return 0;
}
Exemplo n.º 15
0
PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
{
    PyObject *object;
    Py_ssize_t i;
    Py_ssize_t start;
    Py_ssize_t end;
    PyObject *res;
    unsigned char *outp;
    int ressize;
    Py_UCS4 c;

    if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) {
        const unsigned char *p;
        if (PyUnicodeDecodeError_GetStart(exc, &start))
            return NULL;
        if (PyUnicodeDecodeError_GetEnd(exc, &end))
            return NULL;
        if (!(object = PyUnicodeDecodeError_GetObject(exc)))
            return NULL;
        p = (const unsigned char*)PyBytes_AS_STRING(object);
        res = PyUnicode_New(4 * (end - start), 127);
        if (res == NULL) {
            Py_DECREF(object);
            return NULL;
        }
        outp = PyUnicode_1BYTE_DATA(res);
        for (i = start; i < end; i++, outp += 4) {
            unsigned char c = p[i];
            outp[0] = '\\';
            outp[1] = 'x';
            outp[2] = Py_hexdigits[(c>>4)&0xf];
            outp[3] = Py_hexdigits[c&0xf];
        }

        assert(_PyUnicode_CheckConsistency(res, 1));
        Py_DECREF(object);
        return Py_BuildValue("(Nn)", res, end);
    }
    if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
        if (PyUnicodeEncodeError_GetStart(exc, &start))
            return NULL;
        if (PyUnicodeEncodeError_GetEnd(exc, &end))
            return NULL;
        if (!(object = PyUnicodeEncodeError_GetObject(exc)))
            return NULL;
    }
    else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) {
        if (PyUnicodeTranslateError_GetStart(exc, &start))
            return NULL;
        if (PyUnicodeTranslateError_GetEnd(exc, &end))
            return NULL;
        if (!(object = PyUnicodeTranslateError_GetObject(exc)))
            return NULL;
    }
    else {
        wrong_exception_type(exc);
        return NULL;
    }

    if (end - start > PY_SSIZE_T_MAX / (1+1+8))
        end = start + PY_SSIZE_T_MAX / (1+1+8);
    for (i = start, ressize = 0; i < end; ++i) {
        /* object is guaranteed to be "ready" */
        c = PyUnicode_READ_CHAR(object, i);
        if (c >= 0x10000) {
            ressize += 1+1+8;
        }
        else if (c >= 0x100) {
            ressize += 1+1+4;
        }
        else
            ressize += 1+1+2;
    }
    res = PyUnicode_New(ressize, 127);
    if (res == NULL) {
        Py_DECREF(object);
        return NULL;
    }
    outp = PyUnicode_1BYTE_DATA(res);
    for (i = start; i < end; ++i) {
        c = PyUnicode_READ_CHAR(object, i);
        *outp++ = '\\';
        if (c >= 0x00010000) {
            *outp++ = 'U';
            *outp++ = Py_hexdigits[(c>>28)&0xf];
            *outp++ = Py_hexdigits[(c>>24)&0xf];
            *outp++ = Py_hexdigits[(c>>20)&0xf];
            *outp++ = Py_hexdigits[(c>>16)&0xf];
            *outp++ = Py_hexdigits[(c>>12)&0xf];
            *outp++ = Py_hexdigits[(c>>8)&0xf];
        }
        else if (c >= 0x100) {
static PyObject *
providedBy(PyObject *ignored, PyObject *ob)
{
  PyObject *result, *cls, *cp;
  
  result = PyObject_GetAttr(ob, str__providedBy__);
  if (result == NULL)
    {
      PyErr_Clear();
      return getObjectSpecification(NULL, ob);
    } 


  /* We want to make sure we have a spec. We can't do a type check
     because we may have a proxy, so we'll just try to get the
     only attribute.
  */
  if (PyObject_TypeCheck(result, &SpecType)
      || 
      PyObject_HasAttr(result, strextends)
      )
    return result;
    
  /*
    The object's class doesn't understand descriptors.
    Sigh. We need to get an object descriptor, but we have to be
    careful.  We want to use the instance's __provides__,l if
    there is one, but only if it didn't come from the class.
  */
  Py_DECREF(result);

  cls = PyObject_GetAttr(ob, str__class__);
  if (cls == NULL)
    return NULL;

  result = PyObject_GetAttr(ob, str__provides__);
  if (result == NULL)
    {      
      /* No __provides__, so just fall back to implementedBy */
      PyErr_Clear();
      result = implementedBy(NULL, cls);
      Py_DECREF(cls);
      return result;
    } 

  cp = PyObject_GetAttr(cls, str__provides__);
  if (cp == NULL)
    {
      /* The the class has no provides, assume we're done: */
      PyErr_Clear();
      Py_DECREF(cls);
      return result;
    }

  if (cp == result)
    {
      /*
        Oops, we got the provides from the class. This means
        the object doesn't have it's own. We should use implementedBy
      */
      Py_DECREF(result);
      result = implementedBy(NULL, cls);
    }

  Py_DECREF(cls);
  Py_DECREF(cp);

  return result;
}
Exemplo n.º 17
0
PyObject *
PyString_Format(PyObject *format, PyObject *args)
{
	char *fmt, *res;
	int fmtcnt, rescnt, reslen, arglen, argidx;
	int args_owned = 0;
	PyObject *result, *orig_args;
	PyObject *dict = NULL;
	if (format == NULL || !PyString_Check(format) || args == NULL) {
		/* ERROR */
		return NULL;
	}
	orig_args = args;
	fmt = PyString_AS_STRING(format);
	fmtcnt = PyString_GET_SIZE(format);
	reslen = rescnt = fmtcnt + 100;
	result = PyString_FromStringAndSize((char *)NULL, reslen);
	if (result == NULL)
		return NULL;
	res = PyString_AsString(result);
	if (PyTuple_Check(args)) {
		arglen = PyTuple_GET_SIZE(args);
		argidx = 0;
	}
	else {
		arglen = -1;
		argidx = -2;
	}
	if (args->ob_type->tp_as_mapping && !PyTuple_Check(args) &&
	    !PyObject_TypeCheck(args, &PyBaseString_Type))
		dict = args;
	while (--fmtcnt >= 0) {
		if (*fmt != '%') {
			if (--rescnt < 0) {
				rescnt = fmtcnt + 100;
				reslen += rescnt;
				if (_PyString_Resize(&result, reslen) < 0)
					return NULL;
				res = PyString_AS_STRING(result)
					+ reslen - rescnt;
				--rescnt;
			}
			*res++ = *fmt++;
		}
		else {
			/* Got a format specifier */
			int flags = 0;
			int width = -1;
			int prec = -1;
			int c = '\0';
			int fill;
			PyObject *v = NULL;
			PyObject *temp = NULL;
			char *pbuf;
			int sign;
			int len;
			char formatbuf[FORMATBUFLEN];
			     /* For format{float,int,char}() */

			fmt++;
			if (*fmt == '(') {
				/* TO DO */
			}
			while (--fmtcnt >= 0) {
				switch (c = *fmt++) {
				case '-': flags |= F_LJUST; continue;
				case '+': flags |= F_SIGN; continue;
				case ' ': flags |= F_BLANK; continue;
				case '#': flags |= F_ALT; continue;
				case '0': flags |= F_ZERO; continue;
				}
				break;
			}
			/* ... */
			if (fmtcnt >= 0) {
				if (c == 'h' || c == 'l' || c == 'L') {
					if (--fmtcnt >= 0)
						c = *fmt++;
				}
			}
			if (fmtcnt < 0) {
				/* ERROR */
				goto error;
			}
			if (c != '%') {
				v = getnextarg(args, arglen, &argidx);
				if (v == NULL)
					goto error;
			}
			sign = 0;
			fill = ' ';
			switch (c) {
			case '%':
				pbuf = "%";
				len = 1;
				break;
			case 's':
				/* Fall through */
			case 'r':
				if (c == 's')
					temp = PyObject_Str(v);
				else {
					/* TO DO */
					goto error;
				}
				if (temp == NULL)
					goto error;
				if (!PyString_Check(temp)) {
					/* XXX Note: this should never happen,
					   since PyObject_Repr() and
					   PyObject_Str() assure this */
					/* ERROR */
					Py_DECREF(temp);
					goto error;
				}
				pbuf = PyString_AS_STRING(temp);
				len = PyString_GET_SIZE(temp);
				if (prec >= 0 && len > prec)
					len = prec;
				break;
			case 'i':
			case 'd':
			case 'u':
			case 'o':
			case 'x':
			case 'X':
				pbuf = formatbuf;

				/* TO DO */
//				len = formatint(pbuf,
//						sizeof(formatbuf),
//						flags, prec, c, v);
				if (len < 0)
					goto error;
				/* only d conversion is signed */
				sign = c == 'd';
				if (flags & F_ZERO)
					fill = '0';
				break;
			case 'e':
			case 'E':
			case 'f':
			case 'g':
			case 'G':
			case 'c':

				printf("FORMAT NOT SUPPORTED YET\n");
				goto error;
			default:
				/* ERROR */
				goto error;
			}
			if (sign) {
				if (*pbuf == '-' || *pbuf == '+') {
					sign = *pbuf++;
					len--;
				}
				else if (flags & F_SIGN)
					sign = '+';
				else if (flags & F_BLANK)
					sign = ' ';
				else
					sign = 0;
			}
			if (width < len)
				width = len;
			if (rescnt - (sign != 0) < width) {
				reslen -= rescnt;
				rescnt = width + fmtcnt + 100;
				reslen += rescnt;
				if (reslen < 0) {
					Py_DECREF(result);
					/* ERROR No mem*/
					return NULL;
				}
				if (_PyString_Resize(&result, reslen) < 0)
					return NULL;
				res = PyString_AS_STRING(result)
					+ reslen - rescnt;
			}
			if (sign) {
				if (fill != ' ')
					*res++ = sign;
				rescnt--;
				if (width > len)
					width--;
			}
			if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
				if (fill != ' ') {
					*res++ = *pbuf++;
					*res++ = *pbuf++;
				}
				rescnt -= 2;
				width -= 2;
				if (width < 0)
					width = 0;
				len -= 2;
			}
			if (width > len && !(flags & F_LJUST)) {
				do {
					--rescnt;
					*res++ = fill;
				} while (--width > len);
			}
			if (fill == ' ') {
				if (sign)
					*res++ = sign;
				if ((flags & F_ALT) &&
				    (c == 'x' || c == 'X')) {
					*res++ = *pbuf++;
					*res++ = *pbuf++;
				}
			}
			memcpy(res, pbuf, len);
			res += len;
			rescnt -= len;
			while (--width >= len) {
				--rescnt;
				*res++ = ' ';
			}
                        if (dict && (argidx < arglen) && c != '%') {
				/* ERROR */
                                goto error;
                        }
			Py_XDECREF(temp);
		} /* '%' */
	} /* until end */
	if (argidx < arglen && !dict) {
		/* ERROR */
		goto error;
	}
	if (args_owned) {
		Py_DECREF(args);
	}
	_PyString_Resize(&result, reslen - rescnt);
	return result;

 error:
	Py_DECREF(result);
	if (args_owned) {
		Py_DECREF(args);
	}
	return NULL;
}
/*
    def __adapt__(self, obj):
        """Adapt an object to the reciever
        """
        if self.providedBy(obj):
            return obj

        for hook in adapter_hooks:
            adapter = hook(self, obj)
            if adapter is not None:
                return adapter

  
*/
static PyObject *
__adapt__(PyObject *self, PyObject *obj)
{
  PyObject *decl, *args, *adapter;
  int implements, i, l;

  decl = providedBy(NULL, obj);
  if (decl == NULL)
    return NULL;

  if (PyObject_TypeCheck(decl, &SpecType))
    {
      PyObject *implied;

      implied = inst_attr(decl, str_implied);
      if (implied == NULL)
        {
          Py_DECREF(decl);
          return NULL;
        }

      implements = PyDict_GetItem(implied, self) != NULL;
      Py_DECREF(decl);
    }
  else
    {
      /* decl is probably a security proxy.  We have to go the long way
         around. 
      */
      PyObject *r;
      r = PyObject_CallFunctionObjArgs(decl, self, NULL);
      Py_DECREF(decl);
      if (r == NULL)
        return NULL;
      implements = PyObject_IsTrue(r);
      Py_DECREF(r);
    }

  if (implements)
    {
      Py_INCREF(obj);
      return obj;
    }

  l = PyList_GET_SIZE(adapter_hooks);
  args = PyTuple_New(2);
  if (args == NULL)
    return NULL;
  Py_INCREF(self);
  PyTuple_SET_ITEM(args, 0, self);
  Py_INCREF(obj);
  PyTuple_SET_ITEM(args, 1, obj);
  for (i = 0; i < l; i++)
    {
      adapter = PyObject_CallObject(PyList_GET_ITEM(adapter_hooks, i), args);
      if (adapter == NULL || adapter != Py_None)
        {
          Py_DECREF(args);
          return adapter;
        }
      Py_DECREF(adapter);
    }

  Py_DECREF(args);

  Py_INCREF(Py_None);
  return Py_None;
}
Exemplo n.º 19
0
 bool IsPyGroupTransform(PyObject * pyobject)
 {
     if(!pyobject) return false;
     return PyObject_TypeCheck(pyobject, &PyOCIO_GroupTransformType);
 }
Exemplo n.º 20
0
PyObject* Flow::create(PyTypeObject* pytype, PyObject* args, PyObject* kwds)
{
  try
  {
    // Pick up the operation
    PyObject* oper = PyDict_GetItemString(kwds, "operation");
    if (!oper)
      throw DataException("missing operation on Flow");
    if (!PyObject_TypeCheck(oper, Operation::metadata->pythonClass))
      throw DataException("flow operation must be of type operation");

    // Pick up the buffer
    PyObject* buf = PyDict_GetItemString(kwds, "buffer");
    if (!buf)
      throw DataException("missing buffer on Flow");
    if (!PyObject_TypeCheck(buf, Buffer::metadata->pythonClass))
      throw DataException("flow buffer must be of type buffer");

    // Pick up the quantity
    PyObject* q1 = PyDict_GetItemString(kwds, "quantity");
    double q2 = q1 ? PythonData(q1).getDouble() : 1.0;

    // Pick up the effectivity dates
    DateRange eff;
    PyObject* eff_start = PyDict_GetItemString(kwds, "effective_start");
    if (eff_start)
    {
      PythonData d(eff_start);
      eff.setStart(d.getDate());
    }
    PyObject* eff_end = PyDict_GetItemString(kwds, "effective_end");
    if (eff_end)
    {
      PythonData d(eff_end);
      eff.setEnd(d.getDate());
    }

    // Pick up the type and create the flow
    Flow *l;
    PyObject* t = PyDict_GetItemString(kwds, "type");
    if (t)
    {
      PythonData d(t);
      if (d.getString() == "flow_end")
        l = new FlowEnd(
          static_cast<Operation*>(oper),
          static_cast<Buffer*>(buf),
          q2
        );
      else if (d.getString() == "flow_fixed_end")
        l = new FlowFixedEnd(
          static_cast<Operation*>(oper),
          static_cast<Buffer*>(buf),
          q2
        );
      else if (d.getString() == "flow_fixed_start")
        l = new FlowFixedStart(
          static_cast<Operation*>(oper),
          static_cast<Buffer*>(buf),
          q2
        );
      else
        l = new FlowStart(
          static_cast<Operation*>(oper),
          static_cast<Buffer*>(buf),
          q2
        );
    }
    else
      l = new FlowStart(
        static_cast<Operation*>(oper),
        static_cast<Buffer*>(buf),
        q2
      );

    // Iterate over extra keywords, and set attributes.   @todo move this responsibility to the readers...
    if (l)
    {
      l->setEffective(eff);
      PyObject *key, *value;
      Py_ssize_t pos = 0;
      while (PyDict_Next(kwds, &pos, &key, &value))
      {
        PythonData field(value);
        PyObject* key_utf8 = PyUnicode_AsUTF8String(key);
        DataKeyword attr(PyBytes_AsString(key_utf8));
        Py_DECREF(key_utf8);
        if (!attr.isA(Tags::effective_end) && !attr.isA(Tags::effective_start)
          && !attr.isA(Tags::operation) && !attr.isA(Tags::buffer)
          && !attr.isA(Tags::quantity) && !attr.isA(Tags::type)
          && !attr.isA(Tags::action))
        {
          const MetaFieldBase* fmeta = l->getType().findField(attr.getHash());
          if (!fmeta && l->getType().category)
            fmeta = l->getType().category->findField(attr.getHash());
          if (fmeta)
            // Update the attribute
            fmeta->setField(l, field);
          else
            l->setProperty(attr.getName(), value);
        }
      };
    }

    // Return the object
    Py_INCREF(l);
    return static_cast<PyObject*>(l);
  }
  catch (...)
  {
    PythonType::evalException();
    return NULL;
  }
}
Exemplo n.º 21
0
int
gdbpy_is_field (PyObject *obj)
{
    return PyObject_TypeCheck (obj, &field_object_type);
}
static int __setattro__(PyObject *self, PyObject *attr_name, PyObject *value)
{
	const char *name = PyString_AsString(attr_name);
	pylal_COMPLEX16FrequencySeries *obj = (pylal_COMPLEX16FrequencySeries *) self;

	if(!strcmp(name, "name")) {
		const char *s = PyString_AsString(value);
		if(PyErr_Occurred())
			return -1;
		if(strlen(s) >= sizeof(obj->series->name)) {
			PyErr_Format(PyExc_ValueError, "name too long \"%s\"", s);
			return -1;
		}
		strcpy(obj->series->name, s);
		return 0;
	}
	if(!strcmp(name, "epoch")) {
		if(!PyObject_TypeCheck(value, &pylal_LIGOTimeGPS_Type)) {
			PyErr_SetObject(PyExc_TypeError, value);
			return -1;
		}
		obj->series->epoch = ((pylal_LIGOTimeGPS *) value)->gps;
		return 0;
	}
	if(!strcmp(name, "f0")) {
		double f0 = PyFloat_AsDouble(value);
		if(PyErr_Occurred())
			return -1;
		obj->series->f0 = f0;
		return 0;
	}
	if(!strcmp(name, "deltaF")) {
		double deltaF = PyFloat_AsDouble(value);
		if(PyErr_Occurred())
			return -1;
		obj->series->deltaF = deltaF;
		return 0;
	}
	if(!strcmp(name, "sampleUnits")) {
		if(!PyObject_TypeCheck(value, &pylal_LALUnit_Type)) {
			PyErr_SetObject(PyExc_TypeError, value);
			return -1;
		}
		obj->series->sampleUnits = ((pylal_LALUnit *) value)->unit;
		return 0;
	}
	if(!strcmp(name, "data")) {
		int n;
		/* require array of double precision complex floats */
		if(!PyArray_Check(value) || (PyArray_TYPE((PyArrayObject *) value) != NPY_CDOUBLE)) {
			PyErr_SetObject(PyExc_TypeError, value);
			return -1;
		}
		/* require exactly 1 dimension */
		if(PyArray_NDIM((PyArrayObject *) value) != 1) {
			PyErr_SetObject(PyExc_ValueError, value);
			return -1;
		}
		n = PyArray_DIM((PyArrayObject *) value, 0);
		if(n != obj->series->data->length)
			obj->series->data = XLALResizeCOMPLEX16Sequence(obj->series->data, 0, n);
		memcpy(obj->series->data->data, PyArray_GETPTR1((PyArrayObject *) value, 0), n * sizeof(*obj->series->data->data));
		return 0;
	}
	PyErr_SetString(PyExc_AttributeError, name);
	return -1;
}
Exemplo n.º 23
0
 Py::Object fromShape(const Py::Tuple& args)
 {
     PyObject *pcObj;
     if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj))
         throw Py::Exception();
     TopoDS_Shape shape;
     try {
         if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) {
             shape = static_cast<Part::TopoShapePy*>(pcObj)->getTopoShapePtr()->getShape();
         } else {
             throw Py::TypeError("the given object is not a shape");
         }
         if (!shape.IsNull()) {
             if (shape.ShapeType() == TopAbs_WIRE) {
                 Path::Toolpath result;
                 bool first = true;
                 Base::Placement last;
                 
                 TopExp_Explorer ExpEdges (shape,TopAbs_EDGE);
                 while (ExpEdges.More()) {
                     const TopoDS_Edge& edge = TopoDS::Edge(ExpEdges.Current());
                     TopExp_Explorer ExpVerts(edge,TopAbs_VERTEX);
                     bool vfirst = true;
                     while (ExpVerts.More()) {
                         const TopoDS_Vertex& vert = TopoDS::Vertex(ExpVerts.Current());
                         gp_Pnt pnt = BRep_Tool::Pnt(vert);
                         Base::Placement tpl;
                         tpl.setPosition(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z()));
                         if (first) {
                             // add first point as a G0 move
                             Path::Command cmd;
                             std::ostringstream ctxt;
                             ctxt << "G0 X" << tpl.getPosition().x << " Y" << tpl.getPosition().y << " Z" << tpl.getPosition().z;
                             cmd.setFromGCode(ctxt.str());
                             result.addCommand(cmd);
                             first = false;
                             vfirst = false;
                         } else {
                             if (vfirst)
                                 vfirst = false;
                             else {
                                 Path::Command cmd;
                                 cmd.setFromPlacement(tpl);
                     
                                 // write arc data if needed
                                 BRepAdaptor_Curve adapt(edge);
                                 if (adapt.GetType() == GeomAbs_Circle) {
                                     gp_Circ circ = adapt.Circle();
                                     gp_Pnt c = circ.Location();
                                     bool clockwise = false;
                                     gp_Dir n = circ.Axis().Direction();
                                     if (n.Z() < 0)
                                         clockwise = true;
                                     Base::Vector3d center = Base::Vector3d(c.X(),c.Y(),c.Z());
                                     // center coords must be relative to last point
                                     center -= last.getPosition();
                                     cmd.setCenter(center,clockwise);
                                 }
                                 result.addCommand(cmd);
                             }
                         }
                         ExpVerts.Next();
                         last = tpl;
                     }
                     ExpEdges.Next();
                 }
                 return Py::asObject(new PathPy(new Path::Toolpath(result)));
             } else {
                 throw Py::TypeError("the given shape must be a wire");
             }
         } else {
             throw Py::TypeError("the given shape is empty");
         }
     }
     catch (const Base::Exception& e) {
         throw Py::RuntimeError(e.what());
     }
     return Py::None();
 }
Exemplo n.º 24
0
int guava_request_on_message_complete(http_parser *parser) {
  guava_conn_t *conn = (guava_conn_t *)parser->data;
  Request *request = (Request *)conn->request;
  guava_server_t *server = conn->server;

  Router *router = NULL;
  Handler *handler = NULL;

  guava_response_t *resp = guava_response_new();
  guava_response_set_conn(resp, conn);

  Py_ssize_t nrouters = PyList_Size(server->routers);

  do {
    router = (Router *)guava_router_get_best_matched_router((PyObject *)server->routers, (PyObject *)request);
    if (router) {
      if (router->router->type == GUAVA_ROUTER_STATIC) {
        guava_handler_static(router->router, conn, ((Request *)conn->request)->req, resp, on_write, on_sendfile);
        break;
      } else {
        handler = (Handler *)PyObject_CallMethod((PyObject *)router, "route", "(O)", request);
        handler->handler->router = router->router;
      }
    }

    for (Py_ssize_t i = 0; i < nrouters; ++i) {
      router = (Router *)PyList_GetItem(server->routers, i);
      if (router->router->type != GUAVA_ROUTER_CUSTOM) {
        /*
         * Cause we already try to get the best matched router
         * But we still need to pass the custome router in case use defined some speciall routes
         */
        continue;
      }
      Handler *h = (Handler *)PyObject_CallMethod((PyObject *)router, "route", "(O)", request);
      if ((PyObject *)h != Py_None) {
        handler = h;
        handler->handler->router = router->router;
        break;
      }
    }

    if (!guava_handler_is_valid(handler->handler) || handler->handler->flags & GUAVA_HANDLER_404) {
      guava_response_404(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    if (handler->handler->flags & GUAVA_HANDLER_REDIRECT) {
      PyObject *location = PyTuple_GetItem(handler->handler->args, 0);
      guava_response_302(resp, PyString_AsString(location));
      guava_response_send(resp, on_write);
      break;
    }

    if (handler->handler->router->type == GUAVA_ROUTER_STATIC) {
      guava_handler_static(handler->handler->router, conn, ((Request *)conn->request)->req, resp, on_write, on_sendfile);
      break;
    }

    PyObject *module_name = NULL;
    if (guava_string_equal_raw(handler->handler->package, ".")) {
      module_name = PyString_FromString(handler->handler->module);
    } else {
      module_name = PyString_FromFormat("%s.%s", handler->handler->package, handler->handler->module);
    }

    PyObject *module = PyImport_Import(module_name);
    Py_DECREF(module_name);

    if (!module) {
      fprintf(stderr, "no module named: %s\n", PyString_AsString(module_name));
      if (PyErr_Occurred()) {
        PyErr_Print();
      }
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    PyObject *cls_name = PyString_FromString(handler->handler->cls);
    PyObject *cls = PyObject_GetAttr(module, cls_name);

    Py_DECREF(module);
    Py_DECREF(cls_name);

    if (!cls) {
      fprintf(stderr, "no cls named: %s\n", PyString_AsString(cls_name));
      if (PyErr_Occurred()) {
        PyErr_Print();
      }
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    Controller *c = (Controller *)PyObject_CallObject(cls, NULL);

    if (!PyObject_TypeCheck(c, &ControllerType)) {
      fprintf(stderr, "You controller class must inherit from guava.controller.Controller\n");
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    Py_DECREF(cls);
    c->resp = resp;
    c->req = ((Request *)conn->request)->req;
    c->router = handler->handler->router;

    PyObject *r = NULL;
    if (handler->handler->args) {
      r = PyObject_CallMethod((PyObject *)c, handler->handler->action, "O", handler->handler->args);
    } else {
      r = PyObject_CallMethod((PyObject *)c, handler->handler->action, NULL);
    }

    if (!r) {
      Py_DECREF(c);
      if (PyErr_Occurred()) {
        PyErr_Print();
      }
      fprintf(stderr, "failed to execute action: %s\n", handler->handler->action);
      guava_response_500(resp, NULL);
      guava_response_send(resp, on_write);
      break;
    }

    if (handler->handler->router->session_store && c->SESSION) {
      guava_request_t *r = ((Request *)conn->request)->req;
      PyObject *sid_cookie = PyDict_GetItemString(r->COOKIES, handler->handler->router->session_store->name);
      guava_session_id_t sid = NULL;

      if (sid) {
        sid = guava_string_new(((Cookie *)sid_cookie)->data.value);
      } else {
        sid = guava_session_new_id();
      }

      guava_session_set(handler->handler->router->session_store, sid, c->SESSION);
    }

    Py_DECREF(c);

    guava_response_send(resp, on_write);
  } while(0);

  Py_XDECREF(handler);
  Py_XDECREF(conn->request);

  return 0;
}
Exemplo n.º 25
0
static PyObject *
dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
    DialectObj *self;
    PyObject *ret = NULL;
    PyObject *dialect = NULL;
    PyObject *delimiter = NULL;
    PyObject *doublequote = NULL;
    PyObject *escapechar = NULL;
    PyObject *lineterminator = NULL;
    PyObject *quotechar = NULL;
    PyObject *quoting = NULL;
    PyObject *skipinitialspace = NULL;
    PyObject *strict = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
                                     "|OOOOOOOOO", dialect_kws,
                                     &dialect,
                                     &delimiter,
                                     &doublequote,
                                     &escapechar,
                                     &lineterminator,
                                     &quotechar,
                                     &quoting,
                                     &skipinitialspace,
                                     &strict))
        return NULL;

    if (dialect != NULL) {
        if (IS_BASESTRING(dialect)) {
            dialect = get_dialect_from_registry(dialect);
            if (dialect == NULL)
                return NULL;
        }
        else
            Py_INCREF(dialect);
        /* Can we reuse this instance? */
        if (PyObject_TypeCheck(dialect, &Dialect_Type) &&
            delimiter == 0 &&
            doublequote == 0 &&
            escapechar == 0 &&
            lineterminator == 0 &&
            quotechar == 0 &&
            quoting == 0 &&
            skipinitialspace == 0 &&
            strict == 0)
            return dialect;
    }

    self = (DialectObj *)type->tp_alloc(type, 0);
    if (self == NULL) {
        Py_XDECREF(dialect);
        return NULL;
    }
    self->lineterminator = NULL;

    Py_XINCREF(delimiter);
    Py_XINCREF(doublequote);
    Py_XINCREF(escapechar);
    Py_XINCREF(lineterminator);
    Py_XINCREF(quotechar);
    Py_XINCREF(quoting);
    Py_XINCREF(skipinitialspace);
    Py_XINCREF(strict);
    if (dialect != NULL) {
#define DIALECT_GETATTR(v, n) \
        if (v == NULL) \
            v = PyObject_GetAttrString(dialect, n)
        DIALECT_GETATTR(delimiter, "delimiter");
        DIALECT_GETATTR(doublequote, "doublequote");
        DIALECT_GETATTR(escapechar, "escapechar");
        DIALECT_GETATTR(lineterminator, "lineterminator");
        DIALECT_GETATTR(quotechar, "quotechar");
        DIALECT_GETATTR(quoting, "quoting");
        DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
        DIALECT_GETATTR(strict, "strict");
        PyErr_Clear();
    }

    /* check types and convert to C values */
#define DIASET(meth, name, target, src, dflt) \
    if (meth(name, target, src, dflt)) \
        goto err
    DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ',');
    DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1);
    DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0);
    DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n");
    DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"');
    DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL);
    DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0);
    DIASET(_set_bool, "strict", &self->strict, strict, 0);

    /* validate options */
    if (dialect_check_quoting(self->quoting))
        goto err;
    if (self->delimiter == 0) {
        PyErr_SetString(PyExc_TypeError,
                        "\"delimiter\" must be an 1-character string");
        goto err;
    }
    if (quotechar == Py_None && quoting == NULL)
        self->quoting = QUOTE_NONE;
    if (self->quoting != QUOTE_NONE && self->quotechar == 0) {
        PyErr_SetString(PyExc_TypeError,
                        "quotechar must be set if quoting enabled");
        goto err;
    }
    if (self->lineterminator == 0) {
        PyErr_SetString(PyExc_TypeError, "lineterminator must be set");
        goto err;
    }

    ret = (PyObject *)self;
    Py_INCREF(self);
err:
    Py_XDECREF(self);
    Py_XDECREF(dialect);
    Py_XDECREF(delimiter);
    Py_XDECREF(doublequote);
    Py_XDECREF(escapechar);
    Py_XDECREF(lineterminator);
    Py_XDECREF(quotechar);
    Py_XDECREF(quoting);
    Py_XDECREF(skipinitialspace);
    Py_XDECREF(strict);
    return ret;
}
Exemplo n.º 26
0
dbtype_t
from_python(pgctx_t *ctx, PyObject *ob)
{
    dbtype_t db;
    char *buf;
    Py_ssize_t length;
    PyObject *items;
    struct tm tm;
    long usec;
    //int i;
    
    if (PyObject_HasAttrString(ob, "__topongo__")) {
        ob = PyObject_CallMethod(ob, "__topongo__", NULL);
        if (PyErr_Occurred())
            return DBNULL;
    }
    if (ob == Py_None) {
        db = DBNULL;
    } else if (ob == pongo_id) {
        db = dbuuid_new(ctx, NULL);
    } else if (ob == pongo_utcnow) {
        db = dbtime_now(ctx);
    } else if (PyBool_Check(ob)) {
        db = dbboolean_new(ctx, ob == Py_True);
    } else if (PyInt_Check(ob)) {
        db = dbint_new(ctx, PyInt_AsLong(ob));
    } else if (PyLong_Check(ob)) {
        db = dbint_new(ctx, PyLong_AsLongLong(ob));
    } else if (PyFloat_Check(ob)) {
        db = dbfloat_new(ctx, PyFloat_AsDouble(ob));
    } else if (PyString_Check(ob)) {
        PyString_AsStringAndSize(ob, &buf, &length);
        // FIXME:
        //db = dbbuffer_new(ctx, buf, length);
        db = dbstring_new(ctx, buf, length);
    } else if (PyUnicode_Check(ob)) {
        ob = PyUnicode_AsUTF8String(ob);
        if (ob) {
            PyString_AsStringAndSize(ob, &buf, &length);
            db = dbstring_new(ctx, buf, length);
            Py_DECREF(ob);
        }
    } else if (PyDateTime_Check(ob)) {
        memset(&tm, 0, sizeof(tm));
        tm.tm_year = PyDateTime_GET_YEAR(ob);
        tm.tm_mon = PyDateTime_GET_MONTH(ob);
        tm.tm_mday = PyDateTime_GET_DAY(ob);
        tm.tm_hour = PyDateTime_DATE_GET_HOUR(ob);
        tm.tm_min = PyDateTime_DATE_GET_MINUTE(ob);
        tm.tm_sec = PyDateTime_DATE_GET_SECOND(ob);
        usec = PyDateTime_DATE_GET_MICROSECOND(ob);
        tm.tm_year -= 1900;
        db = dbtime_newtm(ctx, &tm, usec);
#ifdef WANT_UUID_TYPE
    } else if (PyObject_TypeCheck(ob, uuid_class)) {
        ob = PyObject_CallMethod(ob, "get_bytes", NULL);
        PyString_AsStringAndSize(ob, &buf, &length);
        db = dbuuid_new(ctx, (uint8_t*)buf);
#endif
    } else if (Py_TYPE(ob) == &PongoList_Type) {
        // Resolve proxy types back to their original dbtype
        PongoList *p = (PongoList*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoDict_Type) {
        // Resolve proxy types back to their original dbtype
        PongoDict *p = (PongoDict*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoCollection_Type) {
        // Resolve proxy types back to their original dbtype
        PongoCollection *p = (PongoCollection*)ob;
        db = p->dbptr;
    } else if (PyMapping_Check(ob)) {
        length = PyMapping_Length(ob);
        items = PyMapping_Items(ob);
        if (items) {
            // mapping object implements "items"
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_mapping_cb, items, NOSYNC);
            Py_XDECREF(items);
        } else {
            // mapping object implements iterator protocol
            // don't have to decref the iterator object cuz it self-decrefs
            // upon StopIteration
            PyErr_Clear();
            items = PyObject_GetIter(ob);
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_itermapping_cb, items, NOSYNC);
        }
    } else if (PySequence_Check(ob)) {
        length = PySequence_Length(ob);
        db = dblist_new(ctx);
        dblist_extend(ctx, db, length, _py_sequence_cb, ob, NOSYNC);
    } else {
        // FIXME: Unknown object type
        PyErr_SetObject(PyExc_TypeError, (PyObject*)Py_TYPE(ob));
        db = DBNULL;
    }
    return db;
}
Exemplo n.º 27
0
PyObject* Load::create(PyTypeObject* pytype, PyObject* args, PyObject* kwds)
{
  try
  {
    // Pick up the operation
    PyObject* oper = PyDict_GetItemString(kwds,"operation");
    if (!PyObject_TypeCheck(oper, Operation::metadata->pythonClass))
      throw DataException("load operation must be of type operation");

    // Pick up the resource
    PyObject* res = PyDict_GetItemString(kwds,"resource");
    if (!PyObject_TypeCheck(res, Resource::metadata->pythonClass))
      throw DataException("load resource must be of type resource");

    // Pick up the quantity
    PyObject* q1 = PyDict_GetItemString(kwds,"quantity");
    double q2 = q1 ? PythonData(q1).getDouble() : 1.0;

    // Pick up the effective dates
    DateRange eff;
    PyObject* eff_start = PyDict_GetItemString(kwds,"effective_start");
    if (eff_start)
    {
      PythonData d(eff_start);
      eff.setStart(d.getDate());
    }
    PyObject* eff_end = PyDict_GetItemString(kwds,"effective_end");
    if (eff_end)
    {
      PythonData d(eff_end);
      eff.setEnd(d.getDate());
    }

    // Create the load
    Load *l = new LoadDefault(
      static_cast<Operation*>(oper),
      static_cast<Resource*>(res),
      q2, eff
    );

    // Iterate over extra keywords, and set attributes.   @todo move this responsibility to the readers...
    if (l)
    {
      PyObject *key, *value;
      Py_ssize_t pos = 0;
      while (PyDict_Next(kwds, &pos, &key, &value))
      {
        PythonData field(value);
        PyObject* key_utf8 = PyUnicode_AsUTF8String(key);
        Attribute attr(PyBytes_AsString(key_utf8));
        Py_DECREF(key_utf8);
        if (!attr.isA(Tags::effective_end) && !attr.isA(Tags::effective_start)
          && !attr.isA(Tags::operation) && !attr.isA(Tags::resource)
          && !attr.isA(Tags::quantity) && !attr.isA(Tags::type)
          && !attr.isA(Tags::action))
        {
          const MetaFieldBase* fmeta = l->getType().findField(attr.getHash());
          if (!fmeta && l->getType().category)
            fmeta = l->getType().category->findField(attr.getHash());
          if (fmeta)
            // Update the attribute
            fmeta->setField(l, field);
          else
            PyErr_Format(PyExc_AttributeError,
                "attribute '%S' on '%s' can't be updated",
                key, Py_TYPE(l)->tp_name);
        }
      };
    }

    // Return the object
    Py_INCREF(l);
    return static_cast<PyObject*>(l);
  }
  catch (...)
  {
    PythonType::evalException();
    return NULL;
  }
}
Exemplo n.º 28
0
PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
{
    if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) {
        PyObject *restuple;
        PyObject *object;
        Py_ssize_t i;
        Py_ssize_t start;
        Py_ssize_t end;
        PyObject *res;
        unsigned char *outp;
        Py_ssize_t ressize;
        Py_UCS4 ch;
        if (PyUnicodeEncodeError_GetStart(exc, &start))
            return NULL;
        if (PyUnicodeEncodeError_GetEnd(exc, &end))
            return NULL;
        if (!(object = PyUnicodeEncodeError_GetObject(exc)))
            return NULL;
        if (end - start > PY_SSIZE_T_MAX / (2+7+1))
            end = start + PY_SSIZE_T_MAX / (2+7+1);
        for (i = start, ressize = 0; i < end; ++i) {
            /* object is guaranteed to be "ready" */
            ch = PyUnicode_READ_CHAR(object, i);
            if (ch<10)
                ressize += 2+1+1;
            else if (ch<100)
                ressize += 2+2+1;
            else if (ch<1000)
                ressize += 2+3+1;
            else if (ch<10000)
                ressize += 2+4+1;
            else if (ch<100000)
                ressize += 2+5+1;
            else if (ch<1000000)
                ressize += 2+6+1;
            else
                ressize += 2+7+1;
        }
        /* allocate replacement */
        res = PyUnicode_New(ressize, 127);
        if (res == NULL) {
            Py_DECREF(object);
            return NULL;
        }
        outp = PyUnicode_1BYTE_DATA(res);
        /* generate replacement */
        for (i = start; i < end; ++i) {
            int digits;
            int base;
            ch = PyUnicode_READ_CHAR(object, i);
            *outp++ = '&';
            *outp++ = '#';
            if (ch<10) {
                digits = 1;
                base = 1;
            }
            else if (ch<100) {
                digits = 2;
                base = 10;
            }
            else if (ch<1000) {
                digits = 3;
                base = 100;
            }
            else if (ch<10000) {
                digits = 4;
                base = 1000;
            }
            else if (ch<100000) {
                digits = 5;
                base = 10000;
            }
            else if (ch<1000000) {
                digits = 6;
                base = 100000;
            }
            else {
                digits = 7;
                base = 1000000;
            }
            while (digits-->0) {
                *outp++ = '0' + ch/base;
                ch %= base;
                base /= 10;
            }
            *outp++ = ';';
        }
        assert(_PyUnicode_CheckConsistency(res, 1));
        restuple = Py_BuildValue("(Nn)", res, end);
        Py_DECREF(object);
        return restuple;
    }
    else {
        wrong_exception_type(exc);
        return NULL;
    }
}
Exemplo n.º 29
0
// Trawl a type's dict looking for any slots, signals or properties.
static int trawl_type(PyTypeObject *pytype, qpycore_metaobject *qo,
        QMetaObjectBuilder &builder, QList<const qpycore_pyqtSignal *> &psigs,
        QMap<uint, PropertyData> &pprops)
{
    SIP_SSIZE_T pos = 0;
    PyObject *key, *value;

    while (PyDict_Next(pytype->tp_dict, &pos, &key, &value))
    {
        // See if it is a slot, ie. it has been decorated with pyqtSlot().
        PyObject *sig_obj = PyObject_GetAttr(value,
                qpycore_dunder_pyqtsignature);

        if (sig_obj)
        {
            // Make sure it is a list and not some legitimate attribute that
            // happens to use our special name.
            if (PyList_Check(sig_obj))
            {
                for (SIP_SSIZE_T i = 0; i < PyList_GET_SIZE(sig_obj); ++i)
                {
                    // Set up the skeleton slot.
                    PyObject *decoration = PyList_GET_ITEM(sig_obj, i);
                    Chimera::Signature *slot_signature = Chimera::Signature::fromPyObject(decoration);

                    PyQtSlot *slot = new PyQtSlot(value, (PyObject *)pytype,
                            slot_signature);;

                    qo->pslots.append(slot);
                }
            }

            Py_DECREF(sig_obj);
        }
        else
        {
            PyErr_Clear();

            // Make sure the key is an ASCII string.  Delay the error checking
            // until we know we actually need it.
            const char *ascii_key = sipString_AsASCIIString(&key);

            // See if the value is of interest.
            if (PyObject_TypeCheck(value, &qpycore_pyqtProperty_Type))
            {
                // It is a property.

                if (!ascii_key)
                    return -1;

                Py_INCREF(value);

                qpycore_pyqtProperty *pp = (qpycore_pyqtProperty *)value;

                pprops.insert(pp->pyqtprop_sequence, PropertyData(key, value));

                // See if the property has a scope.  If so, collect all
                // QMetaObject pointers that are not in the super-class
                // hierarchy.
                const QMetaObject *mo = get_scope_qmetaobject(pp->pyqtprop_parsed_type);

                if (mo)
                    builder.addRelatedMetaObject(mo);
            }
            else if (PyObject_TypeCheck(value, &qpycore_pyqtSignal_Type))
            {
                // It is a signal.

                if (!ascii_key)
                    return -1;

                qpycore_pyqtSignal *ps = (qpycore_pyqtSignal *)value;

                // Make sure the signal has a name.
                qpycore_set_signal_name(ps, pytype->tp_name, ascii_key);

                // Add all the overloads.
                do
                {
                    psigs.append(ps);
                    ps = ps->next;
                }
                while (ps);

                Py_DECREF(key);
            }
            else
            {
                PyErr_Clear();
            }
        }
    }

    return 0;
}
Exemplo n.º 30
0
static void
pyg_signal_class_closure_marshal(GClosure *closure,
				 GValue *return_value,
				 guint n_param_values,
				 const GValue *param_values,
				 gpointer invocation_hint,
				 gpointer marshal_data)
{
    PyGILState_STATE state;
    GObject *object;
    PyObject *object_wrapper;
    GSignalInvocationHint *hint = (GSignalInvocationHint *)invocation_hint;
    gchar *method_name, *tmp;
    PyObject *method;
    PyObject *params, *ret;
    guint i, len;

    state = pyglib_gil_state_ensure();

    g_return_if_fail(invocation_hint != NULL);
    /* get the object passed as the first argument to the closure */
    object = g_value_get_object(&param_values[0]);
    g_return_if_fail(object != NULL && G_IS_OBJECT(object));

    /* get the wrapper for this object */
    object_wrapper = pygobject_new(object);
    g_return_if_fail(object_wrapper != NULL);

    /* construct method name for this class closure */
    method_name = g_strconcat("do_", g_signal_name(hint->signal_id), NULL);

    /* convert dashes to underscores.  For some reason, g_signal_name
     * seems to convert all the underscores in the signal name to
       dashes??? */
    for (tmp = method_name; *tmp != '\0'; tmp++)
	if (*tmp == '-') *tmp = '_';

    method = PyObject_GetAttrString(object_wrapper, method_name);
    g_free(method_name);

    if (!method) {
	PyErr_Clear();
	Py_DECREF(object_wrapper);
	pyglib_gil_state_release(state);
	return;
    }
    Py_DECREF(object_wrapper);

    /* construct Python tuple for the parameter values; don't copy boxed values
       initially because we'll check after the call to see if a copy is needed. */
    params = PyTuple_New(n_param_values - 1);
    for (i = 1; i < n_param_values; i++) {
	PyObject *item = pyg_value_as_pyobject(&param_values[i], FALSE);

	/* error condition */
	if (!item) {
	    Py_DECREF(params);
	    pyglib_gil_state_release(state);
	    return;
	}
	PyTuple_SetItem(params, i - 1, item);
    }

    ret = PyObject_CallObject(method, params);

    /* Copy boxed values if others ref them, this needs to be done regardless of
       exception status. */
    len = PyTuple_Size(params);
    for (i = 0; i < len; i++) {
	PyObject *item = PyTuple_GetItem(params, i);
	if (item != NULL && PyObject_TypeCheck(item, &PyGBoxed_Type)
	    && item->ob_refcnt != 1) {
	    PyGBoxed* boxed_item = (PyGBoxed*)item;
	    if (!boxed_item->free_on_dealloc) {
		boxed_item->boxed = g_boxed_copy(boxed_item->gtype, boxed_item->boxed);
		boxed_item->free_on_dealloc = TRUE;
	    }
	}
    }

    if (ret == NULL) {
	PyErr_Print();
	Py_DECREF(method);
	Py_DECREF(params);
	pyglib_gil_state_release(state);
	return;
    }
    Py_DECREF(method);
    Py_DECREF(params);
    if (return_value)
	pyg_value_from_pyobject(return_value, ret);
    Py_DECREF(ret);
    pyglib_gil_state_release(state);
}