Exemplo n.º 1
0
PyObject *
_pyccn_cmd_content_to_bytearray(PyObject *UNUSED(self), PyObject *arg)
{
    PyObject *str, *result;

    if (arg == Py_None)
        Py_RETURN_NONE;
    else if (PyFloat_Check(arg) || PyLong_Check(arg) || _pyccn_Int_Check(arg)) {
        PyObject *py_o;

        py_o = PyObject_Str(arg);
        if (!py_o)
            return NULL;

#if PY_MAJOR_VERSION >= 3
        str = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(py_o),
                                   PyUnicode_GET_SIZE(py_o), NULL);
        Py_DECREF(py_o);
#else
        str = py_o;
#endif
    } else if (PyUnicode_Check(arg)) {
        str = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(arg),
                                   PyUnicode_GET_SIZE(arg), NULL);
    } else
        str = (Py_INCREF(arg), arg);

    if (!str)
        return NULL;

    result = PyByteArray_FromObject(str);
    Py_DECREF(str);

    return result;
}
Exemplo n.º 2
0
static PyObject *pepy_parsed_get_bytes(PyObject *self, PyObject *args) {
	uint64_t start, idx;
	uint8_t b;
	Py_ssize_t len;
	PyObject *byte, *tmp, *ret, *newlist;

	if (!PyArg_ParseTuple(args, "KK:pepy_parsed_get_bytes", &start, &len))
		return NULL;

	/*
	 * XXX: I don't think this is the best way to do this. I want a
	 * ByteArray object to be returned so first put each byte in a
	 * list and then call PyByteArray_FromObject to get the byte array.
	 */
	tmp = PyList_New(len);
	if (!tmp) {
		PyErr_SetString(pepy_error, "Unable to create initial list.");
		return NULL;
	}

	for (idx = 0; idx < len; idx++) {
		if (!ReadByteAtVA(((pepy_parsed *) self)->pe, start + idx, b))
			break;

		byte = PyInt_FromLong(b);
		if (!byte) {
			Py_DECREF(tmp);
			PyErr_SetString(pepy_error, "Unable to create integer object.");
			return NULL;
		}
		PyList_SET_ITEM(tmp, idx, byte);
		Py_DECREF(byte);
	}

	/* Didn't get all of it for some reason, so give back what we have. */
	if (idx < len) {
		newlist = PyList_GetSlice(tmp, 0, idx);
		if (!newlist) {
			PyErr_SetString(pepy_error, "Unable to create new list.");
			return NULL;
		}
		Py_DECREF(tmp);
		tmp = newlist;
	}

	ret = PyByteArray_FromObject(tmp);
	if (!ret) {
		PyErr_SetString(pepy_error, "Unable to create new list.");
		return NULL;
	}
	Py_DECREF(tmp);

	return ret;
}