static PyObject *DoPyRead_Size(nsIInputStream *pI, PRUint32 n)
{
	if (n==(PRUint32)-1) {
		nsresult r;
		Py_BEGIN_ALLOW_THREADS;
		r = pI->Available(&n);
		Py_END_ALLOW_THREADS;
		if (NS_FAILED(r))
			return PyXPCOM_BuildPyException(r);
	}
	if (n==0) { // mozilla will assert if we alloc zero bytes.
		return PyBuffer_New(0);
	}
	char *buf = (char *)nsMemory::Alloc(n);
	if (buf==NULL) {
		PyErr_NoMemory();
		return NULL;
	}
	nsresult r;
	PRUint32 nread;
	Py_BEGIN_ALLOW_THREADS;
	r = pI->Read(buf, n, &nread);
	Py_END_ALLOW_THREADS;
	PyObject *rc = NULL;
	if ( NS_SUCCEEDED(r) ) {
		rc = PyBuffer_New(nread);
		if (rc != NULL) {
			void *ob_buf;
			Py_ssize_t buf_len;
			if (PyObject_AsWriteBuffer(rc, &ob_buf, &buf_len) != 0) {
				// should never fail - we just created it!
				return NULL;
			}

			if ( (buf_len & 0xFFFFFFFF) != buf_len) {
				PyErr_SetString(PyExc_RuntimeError, "Python Buffer length overflows 32-bit in PyObject_AsWriteBuffer");
				return NULL;
			}

			if (buf_len != nread) {
				PyErr_SetString(PyExc_RuntimeError, "New buffer isn't the size we created it!");
				return NULL;
			}
			memcpy(ob_buf, buf, nread);
		}
	} else
		PyXPCOM_BuildPyException(r);
	nsMemory::Free(buf);
	return rc;
}
Example #2
0
static PyObject *Wiimote_read(Wiimote *self, PyObject *args, PyObject *kwds)
{
	static char *kwlist[] = { "flags", "offset", "len", NULL };
	unsigned char flags;
	unsigned int offset;
	Py_ssize_t len;
	void *buf;
	PyObject *pyRetBuf;

	if (!self->wiimote) {
		SET_CLOSED_ERROR;
		return NULL;
	}

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "BII:cwiid.Wiimote.read",
	                                 kwlist, &flags, &offset, &len)) {
		return NULL;
	}

	if (!(pyRetBuf = PyBuffer_New(len))) {
		return NULL;
	}
	if (PyObject_AsWriteBuffer(pyRetBuf, &buf, &len)) {
		Py_DECREF(pyRetBuf);
		return NULL;
	}
	if (cwiid_read(self->wiimote,flags,offset,len,buf)) {
		PyErr_SetString(PyExc_RuntimeError, "Error reading wiimote data");
		Py_DECREF(pyRetBuf);
		return NULL;
	}

	return pyRetBuf;
}
Example #3
0
Py::Object
Image::color_conv(const Py::Tuple& args) {
  _VERBOSE("Image::color_conv");

  args.verify_length(1);
  int format = Py::Int(args[0]);

  int row_len = colsOut * 4;
  PyObject* py_buffer = PyBuffer_New(row_len * rowsOut);
  if (py_buffer ==NULL)
    throw Py::MemoryError("Image::color_conv could not allocate memory");

  void* buf;
  Py_ssize_t buffer_len;
  int ret = PyObject_AsWriteBuffer(py_buffer, &buf, &buffer_len);
  if (ret !=0)
    throw Py::MemoryError("Image::color_conv could not allocate memory");

  agg::rendering_buffer rtmp;
  rtmp.attach(reinterpret_cast<unsigned char*>(buf), colsOut, rowsOut,
	      row_len);

  switch (format) {
  case 0:
    agg::color_conv(&rtmp, rbufOut, agg::color_conv_rgba32_to_bgra32());
    break;
  case 1:
    agg::color_conv(&rtmp, rbufOut, agg::color_conv_rgba32_to_argb32());
    break;
  default:
    throw Py::ValueError("Image::color_conv unknown format");
  }
  PyObject* o = Py_BuildValue("llN", rowsOut, colsOut, py_buffer);
  return Py::asObject(o);
}
Example #4
0
// @pymethod buffer|win32wnet|NCBBuffer|Creates an NCB buffer of the relevant size.
PyObject *
PyWinMethod_NCBBuffer(PyObject *self, PyObject *args)
{
	int size;
	// @pyparm int|size||The number of bytes to allocate.
	if (!PyArg_ParseTuple(args, "i:NCBBuffer", &size))
		return NULL;
	return PyBuffer_New(size);
}
Example #5
0
static PyObject *bits_malloc(PyObject *self, PyObject *args)
{
    Py_ssize_t length;

    if (!PyArg_ParseTuple(args, "n:malloc", &length))
        return NULL;

    return PyBuffer_New(length);
}
Example #6
0
PyObject *engine_buffer_setup(Evas_PyObject *o, PyObject *kwargs)
{
    Evas_Engine_Info_Buffer *einfo;
    int buflen, w, h;
    PyObject *value, *buffer;

    BENCH_START
    evas_output_method_set(o->evas, evas_render_method_lookup("buffer"));
    BENCH_END

    einfo = (Evas_Engine_Info_Buffer *) evas_engine_info_get(o->evas);
    if (!einfo) {
        PyErr_Format(PyExc_SystemError, "Evas is not built with buffer engine support.");
        return NULL;
    }

    einfo->info.func.new_update_region = NULL;
    einfo->info.func.free_update_region = NULL;
    einfo->info.use_color_key = 0;
    einfo->info.alpha_threshold = 0;

    // Class wrapper ensures these kwargs exist.
    if (!PyArg_ParseTuple(PyDict_GetItemString(kwargs, "size"), "ii", &w, &h))
        return 0;

    einfo->info.depth_type = PyLong_AsLong(PyDict_GetItemString(kwargs, "depth"));
    einfo->info.dest_buffer_row_bytes = PyLong_AsLong(PyDict_GetItemString(kwargs, "stride"));
    einfo->info.dest_buffer = 0;
    value = PyDict_GetItemString(kwargs, "buffer");
    if (!value || value == Py_None) {
        buffer = PyBuffer_New(einfo->info.dest_buffer_row_bytes * h);
        if (PyObject_AsWriteBuffer(buffer, &einfo->info.dest_buffer, &buflen) == -1)
            return 0;
    } else {
        if (PyNumber_Check(value)) {
            einfo->info.dest_buffer = (void *) PyLong_AsLong(value);
            buffer = PyBuffer_FromReadWriteMemory(einfo->info.dest_buffer, 
                                                  einfo->info.dest_buffer_row_bytes * h);
        } else {
            if (PyObject_AsWriteBuffer(value, &einfo->info.dest_buffer, &buflen) == -1)
                return 0;
            if (buflen < einfo->info.dest_buffer_row_bytes * h) {
                PyErr_SetString(PyExc_AttributeError, "Buffer not big enough");
                return 0;
            }
            buffer = value;
            Py_INCREF(buffer);
        }
    }

    BENCH_START
    evas_engine_info_set(o->evas, (Evas_Engine_Info *) einfo);
    BENCH_END
    return buffer;
}
Example #7
0
static PyObject *
xpybCookie_reply(xpybCookie *self, PyObject *args)
{
    xcb_generic_error_t *error;
    xcb_generic_reply_t *data;
    PyObject *shim, *reply;
    int is_void;
    void *buf;
    Py_ssize_t len;

    xpybRequest_get_attributes(self->request, &is_void, NULL, NULL);

    /* Check arguments and connection. */
    if (is_void) {
        PyErr_SetString(xpybExcept_base, "Request has no reply.");
        return NULL;
    }
    if (xpybConn_invalid(self->conn))
        return NULL;

    /* Make XCB call */
    data = xcb_wait_for_reply(self->conn->conn, self->cookie.sequence, &error);
    if (xpybError_set(self->conn, error))
        return NULL;
    if (data == NULL) {
        PyErr_SetString(PyExc_IOError, "I/O error on X server connection.");
        return NULL;
    }

    /* Create a shim protocol object */
    shim = PyBuffer_New(32 + data->length * 4);
    if (shim == NULL)
        goto err1;
    if (PyObject_AsWriteBuffer(shim, &buf, &len) < 0)
        goto err2;
    memcpy(buf, data, len);
    free(data);

    /* Call the reply type object to get a new xcb.Reply instance */
    reply = PyObject_CallFunctionObjArgs((PyObject *)self->reply_type, shim, NULL);
    Py_DECREF(shim);
    return reply;

err2:
    Py_DECREF(shim);
err1:
    free(data);
    return NULL;
}
Example #8
0
File: svg.c Project: clones/kaa
PyObject *
render_svg_to_buffer(PyObject *module, PyObject *args, PyObject *kwargs)
{
    int len, w, h, i;
    guchar *svgdata;

    GError *error;
    RsvgHandle *svg;
    GdkPixbuf *pixbuf;
    gboolean res;
    size_cb_data cbdata;

    PyObject *buffer;
    guchar *buffer_ptr;
    
    if (!PyArg_ParseTuple(args, "iis#", &w, &h, &svgdata, &len))
        return NULL;

    cbdata.w = w;
    cbdata.h = h;

    svg = rsvg_handle_new();
    rsvg_handle_set_size_callback(svg, size_cb, &cbdata, NULL);
    res = rsvg_handle_write(svg, svgdata, len, &error);
    res = rsvg_handle_close(svg, &error);
    pixbuf = rsvg_handle_get_pixbuf(svg);
    rsvg_handle_free(svg);

    w = gdk_pixbuf_get_width(pixbuf);
    h = gdk_pixbuf_get_height(pixbuf);

    buffer = PyBuffer_New(w*h*4);
    PyObject_AsWriteBuffer(buffer, (void **)&buffer_ptr, &len);
    memcpy(buffer_ptr, gdk_pixbuf_get_pixels(pixbuf), w*h*4);
    g_object_unref(pixbuf);

    // RGBA to BGRA conversion.
    // FIXME: MMXify.
    for (i = 0; i < w*h*4; i+=4) {
        guchar save = buffer_ptr[i+2];
        buffer_ptr[i+2] = buffer_ptr[i];
        buffer_ptr[i] = save;
    }
    return Py_BuildValue("(iiO)", w, h, buffer);
}
static PyObject *DoPyRead_Buffer(nsIInputStream *pI, PyObject *obBuffer, PRUint32 n)
{
	PRUint32 nread;
	void *buf;
#ifndef VBOX /* unsafe cast on 64-bit hosts. */
	PRUint32 buf_len;
	if (PyObject_AsWriteBuffer(obBuffer, &buf, (Py_ssize_t *)&buf_len) != 0) {
#else   /* VBOX */
# if PY_VERSION_HEX >= 0x02050000 || defined(PY_SSIZE_T_MIN)
        Py_ssize_t buf_len;
# else
        int buf_len;
# endif /* VBOX */
	if (PyObject_AsWriteBuffer(obBuffer, &buf, &buf_len) != 0) {
#endif
		PyErr_Clear();
		PyErr_SetString(PyExc_TypeError, "The buffer object does not have a write buffer!");
		return NULL;
	}
	if (n==(PRUint32)-1) {
		n = buf_len;
	} else {
		if (n > buf_len) {
			NS_WARNING("Warning: PyIInputStream::read() was passed an integer size greater than the size of the passed buffer!  Buffer size used.\n");
			n = buf_len;
		}
	}
	nsresult r;
	Py_BEGIN_ALLOW_THREADS;
	r = pI->Read((char *)buf, n, &nread);
	Py_END_ALLOW_THREADS;
	if ( NS_FAILED(r) )
		return PyXPCOM_BuildPyException(r);
	return PyInt_FromLong(nread);
}

static PyObject *DoPyRead_Size(nsIInputStream *pI, PRUint32 n)
{
	if (n==(PRUint32)-1) {
		nsresult r;
		Py_BEGIN_ALLOW_THREADS;
		r = pI->Available(&n);
		Py_END_ALLOW_THREADS;
		if (NS_FAILED(r))
			return PyXPCOM_BuildPyException(r);
	}
	if (n==0) { // mozilla will assert if we alloc zero bytes.
#if PY_MAJOR_VERSION <= 2
		return PyBuffer_New(0);
#else
		return PyBytes_FromString("");
#endif
	}
	char *buf = (char *)nsMemory::Alloc(n);
	if (buf==NULL) {
		PyErr_NoMemory();
		return NULL;
	}
	nsresult r;
	PRUint32 nread;
	Py_BEGIN_ALLOW_THREADS;
	r = pI->Read(buf, n, &nread);
	Py_END_ALLOW_THREADS;
	PyObject *rc = NULL;
	if ( NS_SUCCEEDED(r) ) {
#if PY_MAJOR_VERSION <= 2
		rc = PyBuffer_New(nread);
		if (rc != NULL) {
			void *ob_buf;
#ifndef VBOX /* unsafe cast on 64-bit hosts. */
			PRUint32 buf_len;
			if (PyObject_AsWriteBuffer(rc, &ob_buf, (Py_ssize_t *)&buf_len) != 0) {
#else   /* VBOX */
# if PY_VERSION_HEX >= 0x02050000 || defined(PY_SSIZE_T_MIN)
                        Py_ssize_t buf_len;
# else
                        int buf_len;
# endif /* VBOX */
			if (PyObject_AsWriteBuffer(rc, &ob_buf, &buf_len) != 0) {
#endif
				// should never fail - we just created it!
				return NULL;
			}
			if (buf_len != nread) {
				PyErr_SetString(PyExc_RuntimeError, "New buffer isnt the size we create it!");
				return NULL;
			}
			memcpy(ob_buf, buf, nread);
		}
#else
        rc = PyBytes_FromStringAndSize(buf, nread);
#endif
	} else
		PyXPCOM_BuildPyException(r);
	nsMemory::Free(buf);
	return rc;
}

static PyObject *PyRead(PyObject *self, PyObject *args)
{
	PyObject *obBuffer = NULL;
	PRUint32 n = (PRUint32)-1;

	nsIInputStream *pI = GetI(self);
	if (pI==NULL)
		return NULL;
	if (PyArg_ParseTuple(args, "|i", (int *)&n))
		// This worked - no args, or just an int.
		return DoPyRead_Size(pI, n);
	// try our other supported arg format.
	PyErr_Clear();
	if (!PyArg_ParseTuple(args, "O|i", &obBuffer, (int *)&n)) {
		PyErr_Clear();
		PyErr_SetString(PyExc_TypeError, "'read()' must be called as (buffer_ob, int_size=-1) or (int_size=-1)");
		return NULL;
	}
	return DoPyRead_Buffer(pI, obBuffer, n);
}


struct PyMethodDef
PyMethods_IInputStream[] =
{
	{ "read", PyRead, 1},
	// The rest are handled as normal
	{NULL}
};
Example #10
0
// @object PyADSVALUE|A tuple:
// @tupleitem 0|object|value|The value as a Python object.
// @tupleitem 1|int|type|The AD type of the value.
PyObject *PyADSIObject_FromADSVALUE(ADSVALUE &v)
{
	PyObject *ob = NULL;
	switch (v.dwType) {
		case ADSTYPE_DN_STRING:
			ob = PyWinObject_FromWCHAR(v.DNString);
			break;
		case ADSTYPE_CASE_EXACT_STRING:
			ob = PyWinObject_FromWCHAR(v.CaseExactString);
			break;
		case ADSTYPE_CASE_IGNORE_STRING:
			ob = PyWinObject_FromWCHAR(v.CaseIgnoreString);
			break;
		case ADSTYPE_PRINTABLE_STRING:
			ob = PyWinObject_FromWCHAR(v.PrintableString);
			break;
		case ADSTYPE_NUMERIC_STRING:
			ob = PyWinObject_FromWCHAR(v.NumericString);
			break;
		case ADSTYPE_BOOLEAN:
			ob = v.Boolean ? Py_True : Py_False;
			Py_INCREF(ob);
			break;
		case ADSTYPE_INTEGER:
			ob = PyInt_FromLong(v.Integer);
			break;
		case ADSTYPE_OCTET_STRING:
			{
			void *buf;
			DWORD bufSize = v.OctetString.dwLength;
			if (!(ob=PyBuffer_New(bufSize)))
				return NULL;
			if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
				Py_DECREF(ob);
				return NULL;
				}
			memcpy(buf, v.OctetString.lpValue, bufSize);
			}
			break;
		case ADSTYPE_UTC_TIME:
			ob = PyWinObject_FromSYSTEMTIME(v.UTCTime);
			break;
		case ADSTYPE_LARGE_INTEGER:
			ob = PyWinObject_FromLARGE_INTEGER(v.LargeInteger);
			break;
		case ADSTYPE_OBJECT_CLASS:
			ob = PyWinObject_FromWCHAR(v.ClassName);
			break;
		case ADSTYPE_PROV_SPECIFIC:
			{
			void *buf;
			DWORD bufSize = v.ProviderSpecific.dwLength;
			if (!(ob=PyBuffer_New(bufSize)))
				return NULL;
			if (!PyWinObject_AsWriteBuffer(ob, &buf, &bufSize)){
				Py_DECREF(ob);
				return NULL;
			}
			memcpy(buf, v.ProviderSpecific.lpValue, bufSize);
			break;
			}
		case ADSTYPE_NT_SECURITY_DESCRIPTOR:
			{
			// Get a pointer to the security descriptor.
			PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)(v.SecurityDescriptor.lpValue);
			DWORD SDSize = v.SecurityDescriptor.dwLength;
			// eeek - we don't pass the length - pywintypes relies on
			// GetSecurityDescriptorLength - make noise if this may bite us.
			if (SDSize != GetSecurityDescriptorLength(pSD))
				PyErr_Warn(PyExc_RuntimeWarning, "Security-descriptor size mis-match");
			ob = PyWinObject_FromSECURITY_DESCRIPTOR(pSD);
			break;
			}
		default:
			{
			char msg[100];
			sprintf(msg, "Unknown ADS type code 0x%x - None will be returned", v.dwType);
			PyErr_Warn(PyExc_RuntimeWarning, msg);
			ob = Py_None;
			Py_INCREF(ob);
		}
	}
	if (ob==NULL)
		return NULL;
	PyObject *ret = Py_BuildValue("Oi", ob, (int)v.dwType);
	Py_DECREF(ob);
	return ret;
}
Example #11
0
PyObject *lightblueobex_readheaders(obex_t *obex, obex_object_t *obj)
{
    PyObject *headers;
    uint8_t hi;
    obex_headerdata_t hv;
    uint32_t hv_size;
    int r;
    PyObject *value = NULL;

    DEBUG("%s()\n", __func__);

    headers = PyDict_New();
    if (headers == NULL)
        return NULL;

    if (obex == NULL || obj == NULL || headers == NULL) {
        DEBUG("\treadheaders() got null argument\n");
        return NULL;
    }

    if (!PyDict_Check(headers)) {
        DEBUG("\treadheaders() arg must be dict\n");
        return NULL;
    }

    while (OBEX_ObjectGetNextHeader(obex, obj, &hi, &hv, &hv_size)) {
        DEBUG("\tread header: 0x%02x\n", hi);
        switch (hi & OBEX_HI_MASK) {
        case OBEX_UNICODE:
        {
            if (hv_size < 2) {
                value = PyUnicode_FromUnicode(NULL, 0);
            } else {
                /* hv_size-2 for 2-byte null terminator */
                int byteorder = OBEX_BIG_ENDIAN;
                value = PyUnicode_DecodeUTF16((const char*)hv.bs, hv_size-2,
                        NULL, &byteorder);
                if (value == NULL) {
                    DEBUG("\terror reading unicode header 0x%02x\n", hi);
                    if (PyErr_Occurred()) {
                        PyErr_Print();
                        PyErr_Clear();  /* let caller set exception */
                    }
                    return NULL;
                }
            }
            break;
        }
        case OBEX_BYTE_STREAM:
        {
            value = PyBuffer_New(hv_size);
            if (value != NULL) {
                void *buf;
                Py_ssize_t buflen;
                if (PyObject_AsWriteBuffer(value, &buf, &buflen) < 0) {
                    Py_DECREF(value);
                    DEBUG("\terror writing to buffer for header 0x%02x\n", hi);
                    return NULL;
                }
                memcpy(buf, hv.bs, buflen);
            }
            break;
        }
        case OBEX_BYTE:
        {
            value = PyInt_FromLong(hv.bq1);
            break;
        }
        case OBEX_INT:
        {
            value = PyLong_FromUnsignedLong(hv.bq4);
            break;
        }
        default:
            DEBUG("\tunknown header id encoding %d\n", (hi & OBEX_HI_MASK));
            return NULL;
        }

        if (value == NULL) {
            if (PyErr_Occurred() == NULL)
                DEBUG("\terror reading headers\n");
            return NULL;
        }
        r = PyDict_SetItem(headers, PyInt_FromLong((long)hi), value);
        Py_DECREF(value);
        if (r < 0) {
            DEBUG("\tPyDict_SetItem() error\n");
            if (PyErr_Occurred()) {
                PyErr_Print();
                PyErr_Clear();  /* let caller set exception */
            }
            return NULL;
        }
    }
    return headers;
}