Exemple #1
0
inline Point coerce_Point(PyObject* obj) {
  // Fast method if the Point is a real Point type.
  PyTypeObject* t2 = get_PointType();
  if (t2 == 0) {
    PyErr_SetString(PyExc_RuntimeError, "Couldn't get Point type.");
    throw std::runtime_error("Couldn't get Point type.");
  }
  if (PyObject_TypeCheck(obj, t2))
    return Point(*(((PointObject*)obj)->m_x));

  PyTypeObject* t = get_FloatPointType();
  if (t == 0) {
    PyErr_SetString(PyExc_RuntimeError, "Couldn't get FloatPoint type.");
    throw std::runtime_error("Couldn't get FloatPoint type.");
  }
  if (PyObject_TypeCheck(obj, t)) {
    FloatPoint* fp = ((FloatPointObject*)obj)->m_x;
    return Point(size_t(fp->x()), size_t(fp->y()));
  }

  PyObject* py_x0 = NULL;
  PyObject* py_y0 = NULL;
  PyObject* py_x1 = NULL;
  PyObject* py_y1 = NULL;

  // Treat 2-element sequences as Points.
  if (PySequence_Check(obj)) {
    if (PySequence_Length(obj) == 2) {
      py_x0 = PySequence_GetItem(obj, 0);
      py_x1 = PyNumber_Int(py_x0);
      Py_DECREF(py_x0);
      if (py_x1 != NULL) {
        long x = PyInt_AsLong(py_x1);
        Py_DECREF(py_x1);
        py_y0 = PySequence_GetItem(obj, 1);
        py_y1 = PyNumber_Int(py_y0);
        Py_DECREF(py_y0);
        if (py_y1 != NULL) {
          long y = PyInt_AsLong(py_y1);
          Py_DECREF(py_y1);
          return Point((size_t)x, (size_t)y);
        }
      }
    }
  }

  PyErr_Clear();
  PyErr_SetString(PyExc_TypeError, "Argument is not a Point (or convertible to one.)");
  throw std::invalid_argument("Argument is not a Point (or convertible to one.)");
}
Exemple #2
0
static int
get_long(PyObject *v, long *p)
{
	long x = PyInt_AsLong(v);
	if (x == -1 && PyErr_Occurred()) {
#ifdef PY_STRUCT_FLOAT_COERCE
		if (PyFloat_Check(v)) {
			PyObject *o;
			int res;
			PyErr_Clear();
			if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
				return -1;
			o = PyNumber_Int(v);
			if (o == NULL)
				return -1;
			res = get_long(o, p);
			Py_DECREF(o);
			return res;
		}
#endif
		if (PyErr_ExceptionMatches(PyExc_TypeError))
			PyErr_SetString(StructError,
					"required argument is not an integer");
		return -1;
	}
	*p = x;
	return 0;
}
Exemple #3
0
static int pyimg_setitem(PyObject *self, Py_ssize_t i, PyObject *v) {
    long tmp;
    struct bug_img *img = &((pyimgObject *) self)->img;
    if(!img->start) {
        PyErr_SetString(PyExc_Exception, "No memory allocated yet.");
        return -1;
    }
    if(i >= img->length || i < 0) {
        PyErr_SetString(PyExc_Exception, "Index out of bounds.");
        return -1;
    }
    if(!PyNumber_Check(v)) {
        PyErr_SetString(PyExc_Exception, "Value must be a number");
        return -1;
    }
    PyObject *n = PyNumber_Int(v);
    if(!n) {
        PyErr_SetString(PyExc_Exception, "Value must be convertable to an integer");
        return -1;
    }
    tmp = PyInt_AS_LONG(n);
    Py_DECREF(n);
    if(tmp > 255) tmp = 255;
    if(tmp < 0) tmp = 0;
    ((unsigned char *) img->start)[i] = tmp;
    return 0;
}
Exemple #4
0
static PyArrayObject * 
PyGSL_PyArray_generate_gsl_vector_view(PyObject *src,
				       int array_type,
				       int argnum)
{
     PyGSL_array_index_t dimension;
     PyObject *tmp;
     PyArrayObject *a_array = NULL;

     FUNC_MESS_BEGIN();
     tmp = PyNumber_Int(src);
     if(!tmp){
	  sprintf(pygsl_error_str, "I could not convert argument number % 3d. to an integer.",
		  argnum);
	 PyErr_SetString(PyExc_TypeError, pygsl_error_str);
	 return NULL;
     }
     dimension = PyInt_AS_LONG(src);
     Py_DECREF(tmp);
     if(dimension <= 0){
	  sprintf(pygsl_error_str, "Argument number % 3d is % 10ld< 0. Its the size of the vector and thus must be positive!",
		  argnum, (long)dimension);
	 PyErr_SetString(PyExc_TypeError, pygsl_error_str);
	 return NULL;
     }
     
     a_array = (PyArrayObject *) PyGSL_New_Array(1, &dimension, array_type);
     if(NULL == a_array){
	  return NULL;
     }
     FUNC_MESS_END();
     return a_array;
}
Exemple #5
0
 bool GetIntFromPyObject(PyObject* object, int* val)
 {
     if(!val || !object) return false;
     
     if( PyInt_Check( object ) )
     {
         *val = static_cast<int>( PyInt_AS_LONG( object ) );
         return true;
     }
     
     if( PyFloat_Check( object ) )
     {
         *val = static_cast<int>( PyFloat_AS_DOUBLE( object ) );
         return true;
     }
     
     PyObject* intObject = PyNumber_Int(object);
     if(intObject)
     {
         *val = static_cast<int>( PyInt_AS_LONG( intObject ) );
         Py_DECREF(intObject);
         return true;
     }
     
     PyErr_Clear();
     return false;
 }
Exemple #6
0
static PyObject *
int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *x = NULL;
	int base = -909;
	static char *kwlist[] = {"x", "base", 0};

	if (type != &PyInt_Type)
		return int_subtype_new(type, args, kwds); /* Wimp out */
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
					 &x, &base))
		return NULL;
	if (x == NULL)
		return PyInt_FromLong(0L);
	if (base == -909)
		return PyNumber_Int(x);
	if (PyString_Check(x))
		return PyInt_FromString(PyString_AS_STRING(x), NULL, base);
#ifdef Py_USING_UNICODE
	if (PyUnicode_Check(x))
		return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
					 PyUnicode_GET_SIZE(x),
					 base);
#endif
	PyErr_SetString(PyExc_TypeError,
			"int() can't convert non-string with explicit base");
	return NULL;
}
static PyObject *
grp_getgrgid(PyObject *self, PyObject *pyo_id)
{
    PyObject *py_int_id;
    gid_t gid;
    struct group *p;

    py_int_id = PyNumber_Int(pyo_id);
    if (!py_int_id)
            return NULL;
    if (!_Py_Gid_Converter(py_int_id, &gid)) {
        Py_DECREF(py_int_id);
        return NULL;
    }
    Py_DECREF(py_int_id);

    if ((p = getgrgid(gid)) == NULL) {
        if (gid < 0)
            PyErr_Format(PyExc_KeyError,
                         "getgrgid(): gid not found: %ld", (long)gid);
        else
            PyErr_Format(PyExc_KeyError,
                         "getgrgid(): gid not found: %lu", (unsigned long)gid);
        return NULL;
    }
    return mkgrent(p);
}
static int int_from_pyobj(int* v,PyObject *obj,const char *errmess) {
  PyObject* tmp = NULL;
  if (PyInt_Check(obj)) {
    *v = (int)PyInt_AS_LONG(obj);
    return 1;
  }
  tmp = PyNumber_Int(obj);
  if (tmp) {
    *v = PyInt_AS_LONG(tmp);
    Py_DECREF(tmp);
    return 1;
  }
  if (PyComplex_Check(obj))
    tmp = PyObject_GetAttrString(obj,"real");
  else if (PyString_Check(obj) || PyUnicode_Check(obj))
    /*pass*/;
  else if (PySequence_Check(obj))
    tmp = PySequence_GetItem(obj,0);
  if (tmp) {
    PyErr_Clear();
    if (int_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}
    Py_DECREF(tmp);
  }
  {
    PyObject* err = PyErr_Occurred();
    if (err==NULL) err = uts_scsmfo_error;
    PyErr_SetString(err,errmess);
  }
  return 0;
}
Exemple #9
0
int pyobject_to_int(PyObject *res) {
    int ret; PyObject *tmp;
    tmp = PyNumber_Int(res);
    if (tmp == NULL) ret = (PyObject_IsTrue(res)) ? 1 : 0;
    else ret = (int)PyInt_AS_LONG(tmp);

    return ret;
}
static	int _parseSequenceInt(PyObject* e, int i, int *x)
{
	PyObject	*p;
	if((p = PySequence_GetItem(e,i)) && (p = PyNumber_Int(p))){
		*x=PyInt_AS_LONG(p);
		return 1;
		}
	return 0;
}
Exemple #11
0
//-----------------------------------------------------------------------------
// NumberVar_GetValue()
//   Returns the value stored at the given array position.
//-----------------------------------------------------------------------------
static PyObject *NumberVar_GetValue(
    udt_NumberVar *var,                 // variable to determine value for
    unsigned pos)                       // array position
{
    PyObject *result, *stringObj;
    char stringValue[200];
    long integerValue;
    ub4 stringLength;
    sword status;

    if (var->type == &vt_Boolean || var->type == &vt_Integer) {
        status = OCINumberToInt(var->environment->errorHandle, &var->data[pos],
                sizeof(long), OCI_NUMBER_SIGNED, (dvoid*) &integerValue);
        if (Environment_CheckForError(var->environment, status,
                "NumberVar_GetValue(): as integer") < 0)
            return NULL;

        if (var->type == &vt_Boolean)
            return PyBool_FromLong(integerValue);
#if PY_MAJOR_VERSION >= 3
        return PyLong_FromLong(integerValue);
#else
        return PyInt_FromLong(integerValue);
#endif
    }

    if (var->type == &vt_NumberAsString || var->type == &vt_LongInteger) {
        stringLength = sizeof(stringValue);
        status = OCINumberToText(var->environment->errorHandle,
                &var->data[pos],
                (text*) var->environment->numberToStringFormatBuffer.ptr,
                var->environment->numberToStringFormatBuffer.size, NULL, 0,
                &stringLength, (unsigned char*) stringValue);
        if (Environment_CheckForError(var->environment, status,
                "NumberVar_GetValue(): as string") < 0)
            return NULL;
        stringObj = cxString_FromEncodedString(stringValue, stringLength,
                var->environment->encoding);
        if (!stringObj)
            return NULL;
        if (var->type == &vt_NumberAsString)
            return stringObj;
#if PY_MAJOR_VERSION >= 3
        result = PyNumber_Long(stringObj);
#else
        result = PyNumber_Int(stringObj);
#endif
        Py_DECREF(stringObj);
        if (result || !PyErr_ExceptionMatches(PyExc_ValueError))
            return result;
        PyErr_Clear();
    }

    return OracleNumberToPythonFloat(var->environment, &var->data[pos]);
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
  PyNumberMethods *m;
  const char *name = NULL;
  PyObject *res = NULL;
#if PY_VERSION_HEX < 0x03000000
  if (PyInt_Check(x) || PyLong_Check(x))
#else
  if (PyLong_Check(x))
#endif
    return Py_INCREF(x), x;
  m = Py_TYPE(x)->tp_as_number;
#if PY_VERSION_HEX < 0x03000000
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Int(x);
  }
  else if (m && m->nb_long) {
    name = "long";
    res = PyNumber_Long(x);
  }
#else
  if (m && m->nb_int) {
    name = "int";
    res = PyNumber_Long(x);
  }
#endif
  if (res) {
#if PY_VERSION_HEX < 0x03000000
    if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
    if (!PyLong_Check(res)) {
#endif
      PyErr_Format(PyExc_TypeError,
                   "__%s__ returned non-%s (type %.200s)",
                   name, name, Py_TYPE(res)->tp_name);
      Py_DECREF(res);
      return NULL;
    }
  }
  else if (!PyErr_Occurred()) {
    PyErr_SetString(PyExc_TypeError,
                    "an integer is required");
  }
  return res;
}

static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
  Py_ssize_t ival;
  PyObject* x = PyNumber_Index(b);
  if (!x) return -1;
  ival = PyInt_AsSsize_t(x);
  Py_DECREF(x);
  return ival;
}
Exemple #13
0
static INLINE PY_LONG_LONG __pyx_PyInt_AsLongLong(PyObject* x) {
    if (PyInt_CheckExact(x)) {
        return PyInt_AS_LONG(x);
    }
    else if (PyLong_CheckExact(x)) {
        return PyLong_AsLongLong(x);
    }
    else {
        PY_LONG_LONG val;
        PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1;
        val = __pyx_PyInt_AsLongLong(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
Exemple #14
0
PyObjectHandle LuaToPythonConverter::convertToInt(lua_State* L, int index) {
  fixIndex(L, index);

  if (auto ref = getOpaqueRef(L, index)) {
    PyObjectHandle obj(PyNumber_Int(ref->obj.get()));
    checkPythonError(obj, L, "convertToInt(ref)");
    return obj;
  }
  int type = lua_type(L, index);
  if (type != LUA_TNUMBER) {
    luaL_error(L, "Invalid type for convertToInt: %d", type);
  }
  double val = lua_tonumber(L, index);
  long lval = folly::to<long>(val);
  PyObjectHandle obj(PyInt_FromLong(lval));
  checkPythonError(obj, L, "convertToInt");
  return obj;
}
Exemple #15
0
static PyArrayObject * 
PyGSL_PyArray_generate_gsl_matrix_view(PyObject *src,
				      int array_type,
				      int argnum)
{
     PyObject *tmp;
     PyArrayObject *a_array = NULL;

     PyGSL_array_index_t dimensions[2];
     int i;

     FUNC_MESS_BEGIN();     
     if(!PySequence_Check(src) || PySequence_Size(src) != 2){
	  sprintf(pygsl_error_str, "I need a sequence of two elements as argument number % 3d",
		  argnum);
	 PyErr_SetString(PyExc_TypeError, pygsl_error_str);
	 return NULL;

     }

     for(i = 0; i<2; i++){
	  tmp = PyNumber_Int(PySequence_GetItem(src, i));
	  if(!tmp){
	       sprintf(pygsl_error_str, "I could not convert argument number % 3d. for dimension %3d to an integer.",
		       argnum, i);
	       PyErr_SetString(PyExc_TypeError, pygsl_error_str);
	       return NULL;
	  }
	  dimensions[i] = PyInt_AS_LONG(tmp);
	  Py_DECREF(tmp);
	  if(dimensions[i] <= 0){
	       sprintf(pygsl_error_str, "Argument number % 3d is % 10ld< 0. Its the size of the vector and thus must be positive!",
		       argnum, (long)dimensions[i]);
	       PyErr_SetString(PyExc_TypeError, pygsl_error_str);
	       return NULL;
	  }

     }     
     a_array = (PyArrayObject *) PyGSL_New_Array(2, dimensions, array_type);
     if(NULL == a_array){
	  return NULL;
     }
     return a_array;
}
Exemple #16
0
static PyObject *
grp_getgrgid(PyObject *self, PyObject *pyo_id)
{
    PyObject *py_int_id;
    unsigned int gid;
    struct group *p;

    py_int_id = PyNumber_Int(pyo_id);
    if (!py_int_id)
	    return NULL;
    gid = PyInt_AS_LONG(py_int_id);
    Py_DECREF(py_int_id);

    if ((p = getgrgid(gid)) == NULL) {
	PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid);
        return NULL;
    }
    return mkgrent(p);
}
Exemple #17
0
static INLINE unsigned PY_LONG_LONG __pyx_PyInt_AsUnsignedLongLong(PyObject* x) {
    if (PyInt_CheckExact(x)) {
        long val = PyInt_AS_LONG(x);
        if (unlikely(val < 0)) {
            PyErr_SetString(PyExc_TypeError, "Negative assignment to unsigned type.");
            return (unsigned PY_LONG_LONG)-1;
        }
        return val;
    }
    else if (PyLong_CheckExact(x)) {
        return PyLong_AsUnsignedLongLong(x);
    }
    else {
        PY_LONG_LONG val;
        PyObject* tmp = PyNumber_Int(x); if (!tmp) return (PY_LONG_LONG)-1;
        val = __pyx_PyInt_AsUnsignedLongLong(tmp);
        Py_DECREF(tmp);
        return val;
    }
}
Exemple #18
0
static int
get_wrapped_long(PyObject *v, long *p)
{
	if (get_long(v, p) < 0) {
		if (PyLong_Check(v) &&
		    PyErr_ExceptionMatches(PyExc_OverflowError)) {
			PyObject *wrapped;
			long x;
			PyErr_Clear();
#ifdef PY_STRUCT_FLOAT_COERCE
			if (PyFloat_Check(v)) {
				PyObject *o;
				int res;
				PyErr_Clear();
				if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
					return -1;
				o = PyNumber_Int(v);
				if (o == NULL)
					return -1;
				res = get_wrapped_long(o, p);
				Py_DECREF(o);
				return res;
			}
#endif
			if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0)
				return -1;
			wrapped = PyNumber_And(v, pylong_ulong_mask);
			if (wrapped == NULL)
				return -1;
			x = (long)PyLong_AsUnsignedLong(wrapped);
			Py_DECREF(wrapped);
			if (x == -1 && PyErr_Occurred())
				return -1;
			*p = x;
		} else {
			return -1;
		}
	}
	return 0;
}
Exemple #19
0
static int
typecast_cmp(PyObject *obj1, PyObject* obj2)
{
    typecastObject *self = (typecastObject*)obj1;
    typecastObject *other = NULL;
    PyObject *number = NULL;
    Py_ssize_t i, j;
    int res = -1;

    if (PyObject_TypeCheck(obj2, &typecastType)) {
        other = (typecastObject*)obj2;
    }
    else {
        number = PyNumber_Int(obj2);
    }

    Dprintf("typecast_cmp: other = %p, number = %p", other, number);

    for (i=0; i < PyObject_Length(self->values) && res == -1; i++) {
        long int val = PyInt_AsLong(PyTuple_GET_ITEM(self->values, i));

        if (other != NULL) {
            for (j=0; j < PyObject_Length(other->values); j++) {
                if (PyInt_AsLong(PyTuple_GET_ITEM(other->values, j)) == val) {
                    res = 0; break;
                }
            }
        }

        else if (number != NULL) {
            if (PyInt_AsLong(number) == val) {
                res = 0; break;
            }
        }
    }

    Py_XDECREF(number);
    return res;
}
Exemple #20
0
static int
get_wrapped_ulong(PyObject *v, unsigned long *p)
{
	long x = (long)PyLong_AsUnsignedLong(v);
	if (x == -1 && PyErr_Occurred()) {
		PyObject *wrapped;
		PyErr_Clear();
#ifdef PY_STRUCT_FLOAT_COERCE
		if (PyFloat_Check(v)) {
			PyObject *o;
			int res;
			PyErr_Clear();
			if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
				return -1;
			o = PyNumber_Int(v);
			if (o == NULL)
				return -1;
			res = get_wrapped_ulong(o, p);
			Py_DECREF(o);
			return res;
		}
#endif
		wrapped = PyNumber_And(v, pylong_ulong_mask);
		if (wrapped == NULL)
			return -1;
		if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0) {
			Py_DECREF(wrapped);
			return -1;
		}
		x = (long)PyLong_AsUnsignedLong(wrapped);
		Py_DECREF(wrapped);
		if (x == -1 && PyErr_Occurred())
			return -1;
	}
	*p = (unsigned long)x;
	return 0;
}
CLocaLogicImpl::TScriptError CLocaLogicImpl::RunScript(
	PyObject* main_module, PyObject* global_dict,
	const TDesC8& aName, TInt& max_seen_priority,
	PyObject* dict_general, PyObject* dict_devstats, 
	PyObject* dict_msgstats,
	TInt& aMessageCode, TDes& aWithName,
	TDes& aWithTitle, auto_ptr<HBufC8>& aBody,
	TDes& aErrorMessage, const TDesC8& aMac)
{
	PyObject* func=PyDict_GetItemString(global_dict, 
		(const char*)aName.Ptr());
	if (!func) return EIgnored;

	python_ptr<PyObject> res(PyObject_CallFunction(func, "(OOO)",
		dict_general, dict_devstats, dict_msgstats));
	if (! res.get() ) {
		aErrorMessage=_L("Call to function failed ");
		return EPythonError;
	} else {
		if (! PyTuple_Check(res.get()) ) {
			aErrorMessage=_L("Return from Python script is not a tuple");
			return EOtherError;
		} else {
			TInt priority=-1;
			PyObject *with_name, *with_title, *with_body;
			{
				PyObject *priority_num;
				priority_num=PyTuple_GetItem(res.get(), 0);
				python_ptr<PyObject> priority_int(
					PyNumber_Int(priority_num));
				if (priority_int.get()) {
					priority=PyInt_AsLong(priority_int.get());
				} else {
					aErrorMessage=_L("First return from Python script could not be converted to an integer. ");
					return EOtherError;
				}
				if (priority<=0) return EIgnored;
				if (priority<max_seen_priority) return EIgnored;
			}
			{
				PyObject* msgcode_num=PyTuple_GetItem(res.get(), 1);
				python_ptr<PyObject> msgcode_int(
					PyNumber_Int(msgcode_num));
				if (msgcode_int.get()) {
					TInt code=PyInt_AsLong(msgcode_int.get());
					if (iAcceptedMessages->HasBeenAcceptedL(aMac, code)) {
						return EIgnored;
					}
					aMessageCode=PyInt_AsLong(msgcode_int.get());
				} else {
					aErrorMessage=_L("Second return from Python script could not be converted to an integer. ");
					return EOtherError;
				}
			}
			with_name=PyTuple_GetItem(res.get(), 2);
			with_title=PyTuple_GetItem(res.get(), 3);
			with_body=PyTuple_GetItem(res.get(), 4);
			if (!with_name || !with_title || !with_body) {
				aErrorMessage=_L("Python script returned wrong number of values");
				return EOtherError;
			} else {
				if (!IsPythonString(with_name)) {
					aErrorMessage=_L("Third return (name) from Python script could not be converted to a string");
					return EOtherError;
				}
				if (!IsPythonString(with_title)) {
					aErrorMessage=_L("Fourth return (title) from Python script could not be converted to a string");
					return EOtherError;
				}
				if (!IsPythonString(with_body)) {
					aErrorMessage=_L("Fifth return (body) from Python script could not be converted to a string");
					return EOtherError;
				}
				ConvertFromPythonString(aWithName, with_name);
				ConvertFromPythonString(aWithTitle, with_title);
				ConvertFromPythonString(aBody, with_body);
				max_seen_priority=priority;
				return EHighestPriority;
			}
		}
	}
}
Exemple #22
0
//-----------------------------------------------------------------------------
// NumberVar_GetValue()
//   Returns the value stored at the given array position.
//-----------------------------------------------------------------------------
static PyObject *NumberVar_GetValue(
    udt_NumberVar *var,                 // variable to determine value for
    unsigned pos)                       // array position
{
    PyObject *result, *stringObj;
    char stringValue[200];
    long integerValue;
    ub4 stringLength;
    sword status;

#if PY_MAJOR_VERSION < 3
    if (var->type == &vt_Integer || var->type == &vt_Boolean) {
#else
    if (var->type == &vt_Boolean) {
#endif
        status = OCINumberToInt(var->environment->errorHandle, &var->data[pos],
                sizeof(long), OCI_NUMBER_SIGNED, (dvoid*) &integerValue);
        if (Environment_CheckForError(var->environment, status,
                "NumberVar_GetValue(): as integer") < 0)
            return NULL;
#if PY_MAJOR_VERSION < 3
        if (var->type == &vt_Integer)
            return PyInt_FromLong(integerValue);
#endif
        return PyBool_FromLong(integerValue);
    }

    if (var->type == &vt_NumberAsString || var->type == &vt_LongInteger) {
        stringLength = sizeof(stringValue);
        status = OCINumberToText(var->environment->errorHandle,
                &var->data[pos],
                (text*) var->environment->numberToStringFormatBuffer.ptr,
                var->environment->numberToStringFormatBuffer.size, NULL, 0,
                &stringLength, (unsigned char*) stringValue);
        if (Environment_CheckForError(var->environment, status,
                "NumberVar_GetValue(): as string") < 0)
            return NULL;
        stringObj = cxString_FromEncodedString(stringValue, stringLength,
                var->environment->encoding);
        if (!stringObj)
            return NULL;
        if (var->type == &vt_NumberAsString)
            return stringObj;
#if PY_MAJOR_VERSION >= 3
        result = PyNumber_Long(stringObj);
#else
        result = PyNumber_Int(stringObj);
#endif
        Py_DECREF(stringObj);
        if (result || !PyErr_ExceptionMatches(PyExc_ValueError))
            return result;
        PyErr_Clear();
    }

    return OracleNumberToPythonFloat(var->environment, &var->data[pos]);
}


#ifdef SQLT_BFLOAT
//-----------------------------------------------------------------------------
// NativeFloatVar_GetValue()
//   Returns the value stored at the given array position as a float.
//-----------------------------------------------------------------------------
static PyObject *NativeFloatVar_GetValue(
    udt_NativeFloatVar *var,            // variable to determine value for
    unsigned pos)                       // array position
{
    return PyFloat_FromDouble(var->data[pos]);
}


//-----------------------------------------------------------------------------
// NativeFloatVar_SetValue()
//   Set the value of the variable which should be a native double.
//-----------------------------------------------------------------------------
static int NativeFloatVar_SetValue(
    udt_NativeFloatVar *var,            // variable to set value for
    unsigned pos,                       // array position to set
    PyObject *value)                    // value to set
{
    if (!PyFloat_Check(value)) {
        PyErr_SetString(PyExc_TypeError, "expecting float");
        return -1;
    }
    var->data[pos] = PyFloat_AS_DOUBLE(value);
    return 0;
}
Exemple #23
0
PyObject * dataconv_WriteFromOutTuple(PyObject *self, PyObject *args)
{
	PyObject *obArgTypes;
	PyObject *obArgType;
	PyObject *obRetValues;
	PyObject *obPtr;
	PyObject *obOutValue;
	VARTYPE vtArgType;
	BYTE *pbArgs;
	BYTE *pbArg;
	Py_ssize_t cArgs;
	UINT uiIndirectionLevel = 0;
	Py_ssize_t i;
	
	if (!PyArg_ParseTuple(args, "OOO:WriteFromOutTuple", &obRetValues, &obArgTypes, &obPtr))
		return NULL;

	pbArgs = (BYTE *)PyLong_AsVoidPtr(obPtr);
	assert(pbArgs);
	if (!pbArgs)
		return NULL;

	// Nothing to do, oh darn.
	if (obRetValues == Py_None || obArgTypes == Py_None)
	{
		Py_INCREF(Py_None);
		return Py_None;
	}

	if (!PyTuple_Check(obArgTypes))
	{
		PyErr_SetString(PyExc_TypeError, "OLE type description - expecting a tuple");
		return NULL;
	}

	cArgs = PyTuple_Size(obArgTypes);
	if (!PyTuple_Check(obRetValues) && (UINT)PyTuple_Size(obRetValues) != cArgs)
	{
		PyErr_Format(PyExc_TypeError, "Expecting a tuple of length %d or None.", cArgs);
		return NULL;
	}
	
	for(i = 0 ; i < cArgs; i++)
	{
		obArgType = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 0);
		vtArgType = (VARTYPE)PyInt_AS_LONG(obArgType);


		// The following types aren't supported:
		// SAFEARRAY *: This requires support for SAFEARRAYs as a
		//              Python extensions type so we can update the SAFEARRAY
		//              in place.
		// VT_LPWSTR:   This just hasn't been written yet.
		// VT_LPSTR:    This just hasn't been written yet.
		// VT_LPWSTR | VT_BYREF:
		// VT_LPSTR  | VT_BYREF:
		//              These can't be supported since we don't know the correct
		//              memory allocation policy.

		// Find the start of the argument.
		pbArg = pbArgs + PyInt_AS_LONG(PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 1));
		obOutValue = PyTuple_GET_ITEM(obRetValues, i);
	
		if (vtArgType & VT_ARRAY)
		{
			VARENUM rawVT = (VARENUM)(vtArgType & VT_TYPEMASK);
			if (vtArgType & VT_BYREF)
			{
				SAFEARRAY **ppsa = *(SAFEARRAY ***)pbArg;
				SAFEARRAY *psa;
				if (!VALID_BYREF_MISSING(obOutValue))
				{
					if (!PyCom_SAFEARRAYFromPyObject(obOutValue, ppsa, rawVT))
					{
						goto Error;
					}
				}
				else
				{
					SAFEARRAYBOUND rgsabound[1];
					rgsabound[0].lLbound = 0;
					rgsabound[0].cElements = 1;
					psa = SafeArrayCreate(rawVT, 1, rgsabound);
					*ppsa = psa;
				}
			}
			else
			{
				// We can't convert this in place... Ack...
				PyErr_SetString(
					PyExc_TypeError,
					"Inplace SAFEARRAY mucking isn't allowed, doh!");
				goto Error;
				
				SAFEARRAY *psa = *(SAFEARRAY **)pbArg;
				// Here we're updating an existing SafeArray.
				// so we need to handle it very carefully....
				SafeArrayDestroy(psa);
				if (!PyCom_SAFEARRAYFromPyObject(obOutValue, &psa, rawVT))
					return NULL;
			}
		}
			
		// All done with safe array handling.

		PyObject *obUse = NULL;

		switch (vtArgType) {
		case VT_VARIANT | VT_BYREF:
		{
			VARIANT *pvar = *(VARIANT **)pbArg;
			VariantClear(pvar);
			if (!VALID_BYREF_MISSING(obOutValue)) {
				PyCom_VariantFromPyObject(obOutValue, pvar);
			}
			else
			{
				V_VT(pvar) = VT_NULL;
			}
			break;
		}
		case VT_BSTR:
		{
			// This is the normal "BSTR" case, we can't
			// allocate a new BSTR we have to back patch the one
			// thats already there...
			BSTR bstr = *(BSTR *)pbArg;
			BSTR bstrT;
			UINT cch = SysStringLen(bstr);
			if ( PyString_Check(obOutValue) || PyUnicode_Check(obOutValue) )
			{
				if ( !PyWinObject_AsBstr(obOutValue, &bstrT) )
				{
					goto Error;
				}
			}
			else
			{
				// Use str(object) instead!
				obUse = PyObject_Str(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				if ( !PyWinObject_AsBstr(obUse, &bstrT) )
				{
					goto Error;
				}
			}
			
			if (SysStringLen(bstrT) > cch)
			{
				PyErr_Format(
					PyExc_ValueError,
					"Return value[%d] with type BSTR was "
					"longer than the input value: %d",
					i,
					cch);
				goto Error;
			}
				
			// Ok, now we know theres enough room in the source BSTR to
			// modify the sucker in place.
			wcscpy(bstr, bstrT);

			// Free the temp BSTR.
			SysFreeString(bstrT);
			break;
		}
		case VT_BSTR | VT_BYREF:
		{
			BSTR *pbstr = *(BSTR **)pbArg;
			BSTR bstrT = NULL;
			SysFreeString(*pbstr);

			*pbstr = NULL;
			
			if ( PyString_Check(obOutValue) || PyUnicode_Check(obOutValue) )
			{
				if ( !PyWinObject_AsBstr(obOutValue, &bstrT) )
				{
					goto Error;
				}
			}
			else
			{
				// Use str(object) instead!
				obUse = PyObject_Str(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				if (!PyWinObject_AsBstr(obUse, &bstrT) )
				{
					goto Error;
				}
			}
			*pbstr = bstrT;
			break;
		}
		case VT_ERROR | VT_BYREF:
		case VT_HRESULT | VT_BYREF:
		case VT_I4 | VT_BYREF:
		{
			INT *pi = *(INT **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pi = PyInt_AsLong(obUse);
			if (*pi == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI4 | VT_BYREF:
		{
			UINT *pui = *(UINT **)pbArg;
			// special care here as we could be > sys.maxint,
			// in which case we must work with longs.
			// Avoiding PyInt_AsUnsignedLongMask as it doesn't
			// exist in 2.2.
			if (PyLong_Check(obOutValue)) {
				*pui = PyLong_AsUnsignedLong(obOutValue);
			} else {
				// just do the generic "number" thing.
				obUse = PyNumber_Int(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				*pui = (UINT)PyInt_AsLong(obUse);
			}
			if (*pui == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_I2 | VT_BYREF:
		{
			short *ps = *(short **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*ps = (short)PyInt_AsLong(obUse);
			if (*ps == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI2 | VT_BYREF:
		{
			unsigned short *pus = *(unsigned short **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pus = (unsigned short)PyInt_AsLong(obUse);
			if (*pus == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_I1 | VT_BYREF:
		{
			signed char *pb = *(signed char **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pb = (signed char)PyInt_AsLong(obUse);
			if (*pb == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_UI1 | VT_BYREF:
		{
			BYTE *pb = *(BYTE **)pbArg;
			BYTE *pbOutBuffer = NULL;
			if (PyString_Check(obOutValue))
			{
				pbOutBuffer = (BYTE *)PyString_AS_STRING(obOutValue);
				Py_ssize_t cb = PyString_GET_SIZE(obOutValue);
				memcpy(pb, pbOutBuffer, cb);
			}
			// keep this after string check since string can act as buffers
			else if (obOutValue->ob_type->tp_as_buffer)
			{
				DWORD cb;
				if (!PyWinObject_AsReadBuffer(obOutValue, (void **)&pbOutBuffer, &cb))
					goto Error;
				memcpy(pb, pbOutBuffer, cb);
			}
			else
			{
				obUse = PyNumber_Int(obOutValue);
				if (obUse == NULL)
				{
					goto Error;
				}
				*pb = (BYTE)PyInt_AsLong(obUse);
				if (*pb == (UINT)-1 && PyErr_Occurred())
					goto Error;
			}
			break;
		}
		case VT_BOOL | VT_BYREF:
		{
			VARIANT_BOOL *pbool = *(VARIANT_BOOL **)pbArg;
			obUse = PyNumber_Int(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pbool = PyInt_AsLong(obUse) ? VARIANT_TRUE : VARIANT_FALSE;
			if (*pbool == (UINT)-1 && PyErr_Occurred())
				goto Error;
			break;
		}
		case VT_R8 | VT_BYREF:
		{
			double *pdbl = *(double **)pbArg;
			obUse = PyNumber_Float(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pdbl = PyFloat_AsDouble(obUse);
			break;
		}
		case VT_R4 | VT_BYREF:
		{
			float *pfloat = *(float **)pbArg;
			obUse = PyNumber_Float(obOutValue);
			if (obUse == NULL)
			{
				goto Error;
			}
			*pfloat = (float)PyFloat_AsDouble(obUse);
			break;
		}
		case VT_DISPATCH | VT_BYREF:
		{
			PyObject *obIID = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 3);
			IID iid = IID_IDispatch;
			if (obIID != NULL && obIID!=Py_None)
				PyWinObject_AsIID(obIID, &iid);
			IDispatch **pdisp = *(IDispatch ***)pbArg;
			if (!PyCom_InterfaceFromPyInstanceOrObject(
				obOutValue,
				iid,
				(void **)pdisp,
				TRUE))
			{
				goto Error;
			}
			// COM Reference added by InterfaceFrom...
			break;
		}
		case VT_UNKNOWN | VT_BYREF:
		{
			PyObject *obIID = PyTuple_GET_ITEM(PyTuple_GET_ITEM(obArgTypes, i), 3);
			IID iid = IID_IUnknown;
			if (obIID != NULL && obIID!=Py_None)
				PyWinObject_AsIID(obIID, &iid);
			IUnknown **punk = *(IUnknown ***)pbArg;
			if (!PyCom_InterfaceFromPyInstanceOrObject(
				obOutValue,
				iid,
				(void **)punk, TRUE))
			{
				goto Error;
			}
			// COM Reference added by InterfaceFrom...
			break;
		}
		case VT_DATE | VT_BYREF:
		{
			DATE *pdbl = *(DATE **)pbArg;
			if ( !PyWinObject_AsDATE(obOutValue, pdbl) )
			{
				goto Error;
			}
			break;
		}
		case VT_CY | VT_BYREF:
		{
			CY *pcy = *(CY **)pbArg;
			if (!PyObject_AsCurrency(obOutValue, pcy))
				goto Error;
			break;
		}
		case VT_I8 | VT_BYREF:
		{
			LARGE_INTEGER *pi64 = *(LARGE_INTEGER **)pbArg;
			if (!PyWinObject_AsLARGE_INTEGER(obOutValue, pi64))
			{
				goto Error;
			}
			break;
		}
		case VT_UI8 | VT_BYREF:
		{
			ULARGE_INTEGER *pui64 = *(ULARGE_INTEGER **)pbArg;
			if (!PyWinObject_AsULARGE_INTEGER(obOutValue, pui64))
			{
				goto Error;
			}
			break;
		}
		default:
			// could try default, but this error indicates we need to
			// beef up the VARIANT support, rather than default.
			PyErr_Format(PyExc_TypeError, "The VARIANT type is unknown (0x%x).",
			             vtArgType);
			goto Error;
		}
		
		Py_XDECREF(obUse);
	}

	Py_INCREF(Py_None);
	return Py_None;
Error:
	return NULL;
}
Exemple #24
0
/*NUMPY_API
 * PyArray_IntpFromSequence
 * Returns the number of dimensions or -1 if an error occurred.
 * vals must be large enough to hold maxvals
 */
NPY_NO_EXPORT int
PyArray_IntpFromSequence(PyObject *seq, intp *vals, int maxvals)
{
    int nd, i;
    PyObject *op, *err;

    /*
     * Check to see if sequence is a single integer first.
     * or, can be made into one
     */
    if ((nd=PySequence_Length(seq)) == -1) {
        if (PyErr_Occurred()) PyErr_Clear();
#if SIZEOF_LONG >= SIZEOF_INTP && !defined(NPY_PY3K)
        if (!(op = PyNumber_Int(seq))) {
            return -1;
        }
#else
        if (!(op = PyNumber_Long(seq))) {
            return -1;
        }
#endif
        nd = 1;
#if SIZEOF_LONG >= SIZEOF_INTP
        vals[0] = (intp ) PyInt_AsLong(op);
#else
        vals[0] = (intp ) PyLong_AsLongLong(op);
#endif
        Py_DECREF(op);

        /*
         * Check wether there was an error - if the error was an overflow, raise
         * a ValueError instead to be more helpful
         */
        if(vals[0] == -1) {
            err = PyErr_Occurred();
            if (err  &&
                PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
                PyErr_SetString(PyExc_ValueError,
                        "Maximum allowed dimension exceeded");
            }
            if(err != NULL) {
                return -1;
            }
        }
    }
    else {
        for (i = 0; i < MIN(nd,maxvals); i++) {
            op = PySequence_GetItem(seq, i);
            if (op == NULL) {
                return -1;
            }
#if SIZEOF_LONG >= SIZEOF_INTP
            vals[i]=(intp )PyInt_AsLong(op);
#else
            vals[i]=(intp )PyLong_AsLongLong(op);
#endif
            Py_DECREF(op);

            /*
             * Check wether there was an error - if the error was an overflow,
             * raise a ValueError instead to be more helpful
             */
            if(vals[0] == -1) {
                err = PyErr_Occurred();
                if (err  &&
                    PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
                    PyErr_SetString(PyExc_ValueError,
                            "Maximum allowed dimension exceeded");
                }
                if(err != NULL) {
                    return -1;
                }
            }
        }
    }
    return nd;
}
static PyObject *
poll_poll(pollObject *self, PyObject *args) 
{
	PyObject *result_list = NULL, *tout = NULL;
	int timeout = 0, poll_result, i, j;
	PyObject *value = NULL, *num = NULL;

	if (!PyArg_ParseTuple(args, "|O:poll", &tout)) {
		return NULL;
	}

	/* Check values for timeout */
	if (tout == NULL || tout == Py_None)
		timeout = -1;
	else if (!PyNumber_Check(tout)) {
		PyErr_SetString(PyExc_TypeError,
				"timeout must be an integer or None");
		return NULL;
	}
	else {
		tout = PyNumber_Int(tout);
		if (!tout)
			return NULL;
		timeout = PyInt_AsLong(tout);
		Py_DECREF(tout);
	}

	/* Ensure the ufd array is up to date */
	if (!self->ufd_uptodate) 
		if (update_ufd_array(self) == 0)
			return NULL;

	/* call poll() */
	Py_BEGIN_ALLOW_THREADS;
	poll_result = poll(self->ufds, self->ufd_len, timeout);
	Py_END_ALLOW_THREADS;
 
	if (poll_result < 0) {
		PyErr_SetFromErrno(SelectError);
		return NULL;
	} 
       
	/* build the result list */
  
	result_list = PyList_New(poll_result);
	if (!result_list) 
		return NULL;
	else {
		for (i = 0, j = 0; j < poll_result; j++) {
 			/* skip to the next fired descriptor */
 			while (!self->ufds[i].revents) {
 				i++;
 			}
			/* if we hit a NULL return, set value to NULL
			   and break out of loop; code at end will
			   clean up result_list */
			value = PyTuple_New(2);
			if (value == NULL)
				goto error;
			num = PyInt_FromLong(self->ufds[i].fd);
			if (num == NULL) {
				Py_DECREF(value);
				goto error;
			}
			PyTuple_SET_ITEM(value, 0, num);

			/* The &0xffff is a workaround for AIX.  'revents'
			   is a 16-bit short, and IBM assigned POLLNVAL
			   to be 0x8000, so the conversion to int results
			   in a negative number. See SF bug #923315. */
			num = PyInt_FromLong(self->ufds[i].revents & 0xffff);
			if (num == NULL) {
				Py_DECREF(value);
				goto error;
			}
			PyTuple_SET_ITEM(value, 1, num);
 			if ((PyList_SetItem(result_list, j, value)) == -1) {
				Py_DECREF(value);
				goto error;
 			}
 			i++;
 		}
 	}
 	return result_list;

  error:
	Py_DECREF(result_list);
	return NULL;
}
Exemple #26
0
GimpParam *
pygimp_param_from_tuple(PyObject *args, const GimpParamDef *ptype, int nparams)
{
    PyObject *tuple, *item, *r, *g, *b, *x, *y, *w, *h;
    GimpParam *ret;
    int i, j, len;
    gint32 *i32a; gint16 *i16a; guint8 *i8a; gdouble *fa; gchar **sa;

    if (nparams == 0)
	tuple = PyTuple_New(0);
    else if (!PyTuple_Check(args) && nparams == 1)
	tuple = Py_BuildValue("(O)", args);
    else {
	Py_INCREF(args);
	tuple = args;
    }
    if (!PyTuple_Check(tuple)) {
	PyErr_SetString(PyExc_TypeError, "wrong type of parameter");
        Py_DECREF(tuple);
	return NULL;
    }

    if (PyTuple_Size(tuple) != nparams) {
	PyErr_SetString(PyExc_TypeError, "wrong number of parameters");
        Py_DECREF(tuple);
	return NULL;
    }

    ret = g_new(GimpParam, nparams+1);
    for (i = 0; i <= nparams; i++)
	ret[i].type = GIMP_PDB_STATUS;
#define check(expr) if (expr) { \
	    PyErr_SetString(PyExc_TypeError, "wrong parameter type"); \
	    Py_DECREF(tuple); \
	    gimp_destroy_params(ret, nparams); \
	    return NULL; \
	}
#define arraycheck(expr, ar) if (expr) { \
	    PyErr_SetString(PyExc_TypeError, "subscript of wrong type"); \
	    Py_DECREF(tuple); \
	    gimp_destroy_params(ret, nparams); \
	    g_free(ar); \
	    return NULL; \
	}
    for (i = 1; i <= nparams; i++) {
	item = PyTuple_GetItem(tuple, i-1);
	switch (ptype[i-1].type) {
	case GIMP_PDB_INT32:
	    check((x = PyNumber_Int(item)) == NULL);
	    ret[i].data.d_int32 = (gint32)PyInt_AsLong(x);
	    Py_DECREF(x);
	    break;
	case GIMP_PDB_INT16:
	    check((x = PyNumber_Int(item)) == NULL);
	    ret[i].data.d_int16 = (gint16)PyInt_AsLong(x);
	    Py_DECREF(x);
	    break;
	case GIMP_PDB_INT8:
	    check((x = PyNumber_Int(item)) == NULL);
	    ret[i].data.d_int8 = (guint8)PyInt_AsLong(x);
	    Py_DECREF(x);
	    break;
	case GIMP_PDB_FLOAT:
	    check((x = PyNumber_Float(item)) == NULL);
	    ret[i].data.d_float = PyFloat_AsDouble(x);
	    Py_DECREF(x);
	    break;
	case GIMP_PDB_STRING:
	    if (item == Py_None) {
		ret[i].data.d_string = NULL;
		break;
	    }
	    check((x = PyObject_Str(item)) == NULL);
	    ret[i].data.d_string = g_strdup(PyString_AsString(x));
	    Py_DECREF(x);
	    break;
	case GIMP_PDB_INT32ARRAY:
	    check(!PySequence_Check(item));
	    len = PySequence_Length(item);
	    i32a = g_new(gint32, len);
	    for (j = 0; j < len; j++) {
		x = PySequence_GetItem(item, j);
		arraycheck((y=PyNumber_Int(x))==NULL,
			   i32a);
		i32a[j] = PyInt_AsLong(y);
		Py_DECREF(y);
	    }
	    ret[i].data.d_int32array = i32a;
	    break;
	case GIMP_PDB_INT16ARRAY:
	    check(!PySequence_Check(item));
	    len = PySequence_Length(item);
	    i16a = g_new(gint16, len);
	    for (j = 0; j < len; j++) {
		x = PySequence_GetItem(item, j);
		arraycheck((y=PyNumber_Int(x))==NULL,
			   i16a);
		i16a[j] = PyInt_AsLong(y);
		Py_DECREF(y);
	    }
	    ret[i].data.d_int16array = i16a;
	    break;
	case GIMP_PDB_INT8ARRAY:
	    check(!PySequence_Check(item));
	    len = PySequence_Length(item);
	    i8a = g_new(guint8, len);
	    for (j = 0; j < len; j++) {
		x = PySequence_GetItem(item, j);
		arraycheck((y=PyNumber_Int(x))==NULL,
			   i8a);
		i8a[j] = PyInt_AsLong(y);
		Py_DECREF(y);
	    }
	    ret[i].data.d_int8array = i8a;
	    break;
	case GIMP_PDB_FLOATARRAY:
	    check(!PySequence_Check(item));
	    len = PySequence_Length(item);
	    fa = g_new(gdouble, len);
	    for (j = 0; j < len; j++) {
		x = PySequence_GetItem(item, j);
		arraycheck((y=PyNumber_Float(x))==NULL,
			   fa);
		fa[j] = PyFloat_AsDouble(y);
		Py_DECREF(y);
	    }
	    ret[i].data.d_floatarray = fa;
	    break;
	case GIMP_PDB_STRINGARRAY:
	    check(!PySequence_Check(item));
	    len = PySequence_Length(item);
	    sa = g_new(gchar *, len);
	    for (j = 0; j < len; j++) {
		x = PySequence_GetItem(item, j);
		if (x == Py_None) {
		    sa[j] = NULL;
		    continue;
		}
		arraycheck((y=PyObject_Str(x))==NULL,
			   sa);
		sa[j] = g_strdup(PyString_AsString(y));
		Py_DECREF(y);
	    }
	    ret[i].data.d_stringarray = sa;
	    break;
	case GIMP_PDB_COLOR:
	    {
		GimpRGB *rgb, tmprgb;

		if (!pygimp_rgb_check(item)) {
		    check(!PySequence_Check(item) ||
			  PySequence_Length(item) < 3);
		    r = PySequence_GetItem(item, 0);
		    g = PySequence_GetItem(item, 1);
		    b = PySequence_GetItem(item, 2);
		    check(!PyInt_Check(r) || !PyInt_Check(g) ||
			  !PyInt_Check(b));
		    gimp_rgba_set_uchar(&tmprgb, PyInt_AsLong(r),
					PyInt_AsLong(g), PyInt_AsLong(b), 255);
		    rgb = &tmprgb;
		} else {
		    rgb = pyg_boxed_get(item, GimpRGB);
		}
		ret[i].data.d_color = *rgb;
	    }
	    break;
	case GIMP_PDB_REGION:
	    check(!PySequence_Check(item) ||
		  PySequence_Length(item) < 4);
	    x = PySequence_GetItem(item, 0);
	    y = PySequence_GetItem(item, 1);
	    w = PySequence_GetItem(item, 2);
	    h = PySequence_GetItem(item, 3);
	    check(!PyInt_Check(x) || !PyInt_Check(y) ||
		  !PyInt_Check(w) || !PyInt_Check(h));
	    ret[i].data.d_region.x = PyInt_AsLong(x);
	    ret[i].data.d_region.y = PyInt_AsLong(y);
	    ret[i].data.d_region.width = PyInt_AsLong(w);
	    ret[i].data.d_region.height = PyInt_AsLong(h);
	    break;
	case GIMP_PDB_DISPLAY:
	    check(!pygimp_display_check(item));
	    ret[i].data.d_display = ((PyGimpDisplay *)item)->ID;
	    break;
	case GIMP_PDB_IMAGE:
	    if (item == Py_None) {
		ret[i].data.d_image = -1;
		break;
	    }
	    check(!pygimp_image_check(item));
	    ret[i].data.d_image = ((PyGimpImage *)item)->ID;
	    break;
	case GIMP_PDB_LAYER:
	    if (item == Py_None) {
		ret[i].data.d_layer = -1;
		break;
	    }
	    check(!pygimp_layer_check(item));
	    ret[i].data.d_layer = ((PyGimpLayer *)item)->ID;
	    break;
	case GIMP_PDB_CHANNEL:
	    if (item == Py_None) {
		ret[i].data.d_channel = -1;
		break;
	    }
	    check(!pygimp_channel_check(item));
	    ret[i].data.d_channel = ((PyGimpChannel *)item)->ID;
	    break;
	case GIMP_PDB_DRAWABLE:
	    if (item == Py_None) {
		ret[i].data.d_channel = -1;
		break;
	    }
	    check(!pygimp_drawable_check(item));
	    ret[i].data.d_channel = ((PyGimpDrawable *)item)->ID;
	    break;
	case GIMP_PDB_SELECTION:
	    check(!pygimp_layer_check(item));
	    ret[i].data.d_selection = ((PyGimpLayer *)item)->ID;
	    break;
	case GIMP_PDB_BOUNDARY:
	    check(!PyInt_Check(item));
	    ret[i].data.d_boundary = PyInt_AsLong(item);
	    break;
	case GIMP_PDB_VECTORS:
	    check(!pygimp_vectors_check(item));
	    ret[i].data.d_vectors = ((PyGimpVectors *)item)->ID;
	    break;
	case GIMP_PDB_PARASITE:
	    /* can't do anything, since size of GimpParasite is not known */
	    break;
	case GIMP_PDB_STATUS:
	    check(!PyInt_Check(item));
	    ret[i].data.d_status = PyInt_AsLong(item);
	    break;
	case GIMP_PDB_END:
	    break;
	}
#undef check
#undef arraycheck
	ret[i].type = ptype[i-1].type;
    }

    Py_DECREF(tuple);
    return ret;
}
static BOOL PyCom_ExcepInfoFromServerExceptionInstance(PyObject *v, EXCEPINFO *pExcepInfo)
{
	BSTR temp;

	assert(v != NULL);
	assert(pExcepInfo != NULL);
	memset(pExcepInfo, 0, sizeof(EXCEPINFO));

	PyObject *ob = PyObject_GetAttrString(v, "description");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrDescription = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrDescription = temp;
	} else {
		// No description - leave it empty.
		PyErr_Clear();
	}
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "source");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrSource = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrSource = temp;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "helpfile");
	if (ob && ob != Py_None) {
		if ( !PyWinObject_AsBstr(ob, &temp) )
			pExcepInfo->bstrHelpFile = SysAllocString(szBadStringObject);
		else
			pExcepInfo->bstrHelpFile = temp;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "code");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->wCode = (unsigned short)PyInt_AsLong(temp);
			Py_DECREF(temp);
		} // XXX - else - what to do here, apart from call the user a moron :-)
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "scode");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->scode = PyInt_AsLong(temp);
			Py_DECREF(temp);
		} else
			// XXX - again, should we call the user a moron?
			pExcepInfo->scode = E_FAIL;
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);

	ob = PyObject_GetAttrString(v, "helpcontext");
	if (ob && ob != Py_None) {
		PyObject *temp = PyNumber_Int(ob);
		if (temp) {
			pExcepInfo->dwHelpContext = (unsigned short)PyInt_AsLong(temp);
			Py_DECREF(temp);
		}
	}
	else
		PyErr_Clear();
	Py_XDECREF(ob);
	return TRUE;
}
Exemple #28
0
static PyObject *
PyGdkWindow_PropertyChange(PyGdkWindow_Object *self, PyObject *args)
{
    PyObject *py_property, *py_type;
    GdkAtom property, type;
    gint format;
    PyObject *py_mode, *pdata;
    GdkPropMode mode;
    guchar *data = NULL;
    gint nelements;

    if (!PyArg_ParseTuple(args, "OOiOO:GdkWindow.property_change",
			  &py_property, &py_type, &format, &py_mode, &pdata)) {
	return NULL;
    }

    property = pygdk_atom_from_pyobject(py_property);
    if (Pyerr_Occurred())
	return NULL;

    type = pygdk_atom_from_pyobject(py_type);
    if (Pyerr_Occurred())
	return NULL;
    
    if (pygtk_enum_get_value(GDK_TYPE_PROP_MODE, py_mode, (gint *)&mode))
	return NULL;
    switch (format) {
    case 8:
	if (!PyString_Check(pdata)) {
	    PyErr_SetString(PyExc_TypeError, "data not a string and format=8");
	    return NULL;
	}
	data = PyString_AsString(pdata);
	nelements = PyString_Size(pdata);
	break;
    case 16:
	{
	    guint16 *data16;
	    gint i;

	    if (!PySequence_Check(pdata)) {
		PyErr_SetString(PyExc_TypeError,
				"data not a sequence and format=16");
		return NULL;
	    }
	    nelements = PySequence_Length(pdata);
	    data16 = g_new(guint16, nelements);
	    data = (guchar *)data16;
	    for (i = 0; i < nelements; i++) {
		PyObject *item = PySequence_GetItem(pdata, i);
		Py_DECREF(item);
		item = PyNumber_Int(item);
		if (!item) {
		    g_free(data16);
		    PyErr_Clear();
		    PyErr_SetString(PyExc_TypeError,"data element not an int");
		    return NULL;
		}
		data16[i] = PyInt_AsLong(item);
		Py_DECREF(item);
	    }
	}
	break;
    case 32:
	{
	    guint32 *data32;
	    gint i;

	    if (!PySequence_Check(pdata)) {
		PyErr_SetString(PyExc_TypeError,
				"data not a sequence and format=32");
		return NULL;
	    }
	    nelements = PySequence_Length(pdata);
	    data32 = g_new(guint32, nelements);
	    data = (guchar *)data32;
	    for (i = 0; i < nelements; i++) {
		PyObject *item = PySequence_GetItem(pdata, i);
		Py_DECREF(item);
		item = PyNumber_Int(item);
		if (!item) {
		    g_free(data32);
		    PyErr_Clear();
		    PyErr_SetString(PyExc_TypeError,"data element not an int");
		    return NULL;
		}
		data32[i] = PyInt_AsLong(item);
		Py_DECREF(item);
	    }
	}
	break;
    default:
	PyErr_SetString(PyExc_TypeError, "format must be 8, 16 or 32");
	return NULL;
	break;
    }
    gdk_property_change(self->obj, property, type, format, mode, data,
			nelements);
    if (format != 8)
	g_free(data);
    Py_INCREF(Py_None);
    return Py_None;
}
Exemple #29
0
static gboolean
_pygi_marshal_from_py_long (PyObject   *object,   /* in */
                            GIArgument *arg,      /* out */
                            GITypeTag   type_tag,
                            GITransfer  transfer)
{
    PyObject *number;

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

#if PY_MAJOR_VERSION < 3
    {
        PyObject *tmp = PyNumber_Int (object);
        if (tmp) {
            number = PyNumber_Long (tmp);
            Py_DECREF (tmp);
        } else {
            number = PyNumber_Long (object);
        }
    }
#else
    number = PyNumber_Long (object);
#endif

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

    switch (type_tag) {
        case GI_TYPE_TAG_INT8:
        {
            long long_value = PyLong_AsLong (number);
            if (PyErr_Occurred()) {
                break;
            } else if (long_value < G_MININT8 || long_value > G_MAXINT8) {
                PyErr_Format (PyExc_OverflowError, "%ld not in range %ld to %ld",
                              long_value, (long)G_MININT8, (long)G_MAXINT8);
            } else {
                arg->v_int8 = long_value;
            }
            break;
        }

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

        case GI_TYPE_TAG_INT16:
        {
            long long_value = PyLong_AsLong (number);
            if (PyErr_Occurred()) {
                break;
            } else if (long_value < G_MININT16 || long_value > G_MAXINT16) {
                PyErr_Format (PyExc_OverflowError, "%ld not in range %ld to %ld",
                              long_value, (long)G_MININT16, (long)G_MAXINT16);
            } else {
                arg->v_int16 = long_value;
            }
            break;
        }

        case GI_TYPE_TAG_UINT16:
        {
            long long_value = PyLong_AsLong (number);
            if (PyErr_Occurred()) {
                break;
            } else if (long_value < 0 || long_value > G_MAXUINT16) {
                PyErr_Format (PyExc_OverflowError, "%ld not in range %ld to %ld",
                              long_value, (long)0, (long)G_MAXUINT16);
            } else {
                arg->v_uint16 = long_value;
            }
            break;
        }

        case GI_TYPE_TAG_INT32:
        {
            long long_value = PyLong_AsLong (number);
            if (PyErr_Occurred()) {
                break;
            } else if (long_value < G_MININT32 || long_value > G_MAXINT32) {
                PyErr_Format (PyExc_OverflowError, "%ld not in range %ld to %ld",
                              long_value, (long)G_MININT32, (long)G_MAXINT32);
            } else {
                arg->v_int32 = long_value;
            }
            break;
        }

        case GI_TYPE_TAG_UINT32:
        {
            PY_LONG_LONG long_value = PyLong_AsLongLong (number);
            if (PyErr_Occurred()) {
                break;
            } else if (long_value < 0 || long_value > G_MAXUINT32) {
                PyErr_Format (PyExc_OverflowError, "%lld not in range %ld to %lu",
                              long_value, (long)0, (unsigned long)G_MAXUINT32);
            } else {
                arg->v_uint32 = long_value;
            }
            break;
        }

        case GI_TYPE_TAG_INT64:
        {
            /* Rely on Python overflow error and convert to ValueError for 64 bit values */
            arg->v_int64 = PyLong_AsLongLong (number);
            break;
        }

        case GI_TYPE_TAG_UINT64:
        {
            /* Rely on Python overflow error and convert to ValueError for 64 bit values */
            arg->v_uint64 = PyLong_AsUnsignedLongLong (number);
            break;
        }

        default:
            g_assert_not_reached ();
    }

    Py_DECREF (number);

    if (PyErr_Occurred())
        return FALSE;
    return TRUE;
}
static PyObject *Proxy_int(ProxyObject *self)
{
    Proxy__ENSURE_WRAPPED_OR_RETURN_NULL(self);

    return PyNumber_Int(self->wrapped);
}