Beispiel #1
0
static PyObject *Polygon_repr(PyObject *self) {
    char buf[STRBUF_MAX];
    int i, j;
    gpc_polygon * p = ((Polygon *)self)->p;
    gpc_vertex_list *vl;
    gpc_vertex *v;
    PyObject * s = PyString_FromString("Polygon:");
    vl = p->contour;
    for(i=0; i<p->num_contours; i++) {
        if (*((p->hole)+i) == 0)
            sprintf(buf, "\n  <%d:Contour:", i);
        else
            sprintf(buf, "\n  <%d:Hole   :", i);
        PyString_ConcatAndDel(&s, PyString_FromString(buf));
        v = vl->vertex;
        for (j = 0; j < vl->num_vertices; j++) {
            sprintf(buf, " [%d:%#.2g, %#.2g]", j, v->x, v->y);
            PyString_ConcatAndDel(&s, PyString_FromString(buf));
            v++;
        }
        PyString_ConcatAndDel(&s, PyString_FromString(">"));
        vl++;
    }
    return s;
}
Beispiel #2
0
static PyObject *
DiscoDBIter_str(DiscoDBIter *self)
{
    PyObject
        *string = PyString_FromFormat("%s(", Py_TYPE(self)->tp_name),
        *format = NULL;

    if (string == NULL)
        goto Done;

    if (Py_TYPE(self) == &DiscoDBIterItemType)
        format = PyString_FromString("('%s', %s)");
    else
        format = PyString_FromString("'%s'");

    if (format == NULL)
        goto Done;

    PyString_ConcatAndDel(&string, DiscoDBIter_format(self, format, 3));
    PyString_ConcatAndDel(&string, PyString_FromString(")"));

 Done:
    Py_CLEAR(format);

    if (PyErr_Occurred()) {
        Py_CLEAR(string);
        return NULL;
    }

    return string;
}
Beispiel #3
0
static PyObject *
DiscoDB_str(DiscoDB *self)
{
    PyObject
        *string = PyString_FromFormat("%s({", Py_TYPE(self)->tp_name),
        *format = PyString_FromString("'%s': %s"),
        *items = NULL;

    if (string == NULL)
        goto Done;

    if (format == NULL)
        goto Done;

    items = DiscoDB_items(self);
    if (items == NULL)
        goto Done;

    PyString_ConcatAndDel(&string, DiscoDBIter_format((DiscoDBIter *)items, format, 3));
    PyString_ConcatAndDel(&string, PyString_FromString("})"));

 Done:
    Py_CLEAR(format);
    Py_CLEAR(items);

    if (PyErr_Occurred()) {
        Py_CLEAR(string);
        return NULL;
    }

    return string;
}
Beispiel #4
0
PyObject* tostring(PyObject* self, PyObject* gen) {
    if(PyGen_Check(gen)) {
        PyFrameObject* frame = ((PyGenObject*)gen)->gi_frame;

        if(!frame)
            return PyString_FromString("<no frame>");

        int ilineno = PyCode_Addr2Line(frame->f_code, frame->f_lasti);
        PyObject* lineno = PyInt_FromLong(ilineno); // new ref
        PyObject* codeline = PyObject_CallFunctionObjArgs(py_getline,
                             frame->f_code->co_filename, lineno, NULL); // new ref
        Py_CLEAR(lineno);

        if(!codeline) return NULL;

        PyObject* codeline_stripped = PyObject_CallMethod(codeline, "strip", NULL); // new ref
        Py_CLEAR(codeline);

        if(!codeline_stripped) return NULL;

        PyObject* result =
            PyString_FromFormat("  File \"%s\", line %d, in %s\n    %s",
                                PyString_AsString(frame->f_code->co_filename),
                                ilineno, PyString_AsString(frame->f_code->co_name),
                                PyString_AsString(codeline_stripped)); // new ref
        Py_CLEAR(codeline_stripped);
        return result;

    } else if(gen->ob_type == &PyCompose_Type) {
        PyComposeObject* cmps = (PyComposeObject*) gen;
        PyObject* result = NULL;
        PyObject** generator = cmps->generators_base;

        while(generator < cmps->generators_top) {
            PyObject* s = tostring(NULL, *generator++);

            if(!result)
                result = s;

            else {
                PyString_ConcatAndDel(&result, PyString_FromString("\n"));
                PyString_ConcatAndDel(&result, s);
            }
        }

        return result;
    }

    PyErr_SetString(PyExc_TypeError, "tostring() expects generator");
    return NULL;
}
Beispiel #5
0
static PyObject *slot_QSizeF___repr__(PyObject *sipSelf)
{
    QSizeF *sipCpp = reinterpret_cast<QSizeF *>(sipGetCppPtr((sipSimpleWrapper *)sipSelf,sipType_QSizeF));

    if (!sipCpp)
        return 0;


    {
        {
            PyObject * sipRes = 0;

#line 116 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtCore/qsize.sip"
        if (sipCpp->isNull())
        {
        #if PY_MAJOR_VERSION >= 3
            sipRes = PyUnicode_FromString("PyQt5.QtCore.QSizeF()");
        #else
            sipRes = PyString_FromString("PyQt5.QtCore.QSizeF()");
        #endif
        }
        else
        {
            PyObject *w = PyFloat_FromDouble(sipCpp->width());
            PyObject *h = PyFloat_FromDouble(sipCpp->height());
        
            if (w && h)
            {
        #if PY_MAJOR_VERSION >= 3
                sipRes = PyUnicode_FromFormat("PyQt5.QtCore.QSizeF(%R, %R)", w, h);
        #else
                sipRes = PyString_FromString("PyQt5.QtCore.QSizeF(");
                PyString_ConcatAndDel(&sipRes, PyObject_Repr(w));
                PyString_ConcatAndDel(&sipRes, PyString_FromString(", "));
                PyString_ConcatAndDel(&sipRes, PyObject_Repr(h));
                PyString_ConcatAndDel(&sipRes, PyString_FromString(")"));
        #endif
            }
        
            Py_XDECREF(w);
            Py_XDECREF(h);
        }
#line 872 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtCore/sipQtCoreQSizeF.cpp"

            return sipRes;
        }
    }

    return 0;
}
Beispiel #6
0
static PyObject * table_repr(tableobject *self)
{
    PyObject *s;
    const apr_array_header_t *ah;
    apr_table_entry_t *elts;
    int i;

    s = PyString_FromString("{");

    ah = apr_table_elts (self->table);
    elts = (apr_table_entry_t *) ah->elts;

    i = ah->nelts;
    if (i == 0)
        PyString_ConcatAndDel(&s, PyString_FromString("}"));

    while (i--)
        if (elts[i].key)
        {
            PyString_ConcatAndDel(&s, PyString_FromString("'"));
            PyString_ConcatAndDel(&s, PyString_FromString(elts[i].key));
            PyString_ConcatAndDel(&s, PyString_FromString("': '"));
            PyString_ConcatAndDel(&s, PyString_FromString(elts[i].val));
            PyString_ConcatAndDel(&s, PyString_FromString("'"));
            if (i > 0)
                PyString_ConcatAndDel(&s, PyString_FromString(", "));
            else
                PyString_ConcatAndDel(&s, PyString_FromString("}"));
        }

    return s;
}
Beispiel #7
0
static PyObject *
DiscoDBIter_format(DiscoDBIter *self, PyObject *format, int N)
{
    PyObject
        *iterator = PyObject_GetIter((PyObject *)self),
        *string = PyString_FromString(""),
        *item = NULL;
    int i;

    if (iterator == NULL)
        goto Done;

    if (string == NULL)
        goto Done;

    for (i = 0; i < N + 1; i++) {
        item = PyIter_Next(iterator);
        if (item == NULL) {
            if (PyErr_Occurred())
                goto Done;
            else
                break;
        }

        if (i > 0)
            PyString_ConcatAndDel(&string, PyString_FromString(", "));

        if (i < N)
            PyString_ConcatAndDel(&string, PyString_Format(format, item));
        else
            PyString_ConcatAndDel(&string, PyString_FromString("..."));

        if (string == NULL)
            goto Done;

        Py_CLEAR(item);
    }

 Done:
    Py_CLEAR(iterator);
    Py_CLEAR(item);

    if (PyErr_Occurred()) {
        Py_CLEAR(string);
        return NULL;
    }

    return string;
}
Beispiel #8
0
static PyObject *
slice_repr(PySliceObject *r)
{
	PyObject *s, *comma;

	s = PyString_FromString("slice(");
	comma = PyString_FromString(", ");
	PyString_ConcatAndDel(&s, PyObject_Repr(r->start));
	PyString_Concat(&s, comma);
	PyString_ConcatAndDel(&s, PyObject_Repr(r->stop));
	PyString_Concat(&s, comma);
	PyString_ConcatAndDel(&s, PyObject_Repr(r->step));
	PyString_ConcatAndDel(&s, PyString_FromString(")"));
	Py_DECREF(comma);
	return s;
}
Beispiel #9
0
PyObject *
test(const char *msg0, const char *msg1)
{
    PyObject *result = PyString_FromString(msg0);
    PyString_ConcatAndDel(&result, PyString_FromString(msg1));
    return result;
}
Beispiel #10
0
static PyObject *
fortran_getattr(PyFortranObject *fp, char *name) {
    int i,j,k,flag;
    if (fp->dict != NULL) {
        PyObject *v = PyDict_GetItemString(fp->dict, name);
        if (v != NULL) {
            Py_INCREF(v);
            return v;
        }
    }
    for (i=0,j=1;i<fp->len && (j=strcmp(name,fp->defs[i].name));i++);
    if (j==0)
        if (fp->defs[i].rank!=-1) {                   /* F90 allocatable array */
            if (fp->defs[i].func==NULL) return NULL;
            for(k=0;k<fp->defs[i].rank;++k)
                fp->defs[i].dims.d[k]=-1;
            save_def = &fp->defs[i];
            (*(fp->defs[i].func))(&fp->defs[i].rank,fp->defs[i].dims.d,set_data,&flag);
            if (flag==2)
                k = fp->defs[i].rank + 1;
            else
                k = fp->defs[i].rank;
            if (fp->defs[i].data !=NULL) {              /* array is allocated */
                PyObject *v = PyArray_New(&PyArray_Type, k, fp->defs[i].dims.d,
                                          fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY,
                                          NULL);
                if (v==NULL) return NULL;
                /* Py_INCREF(v); */
                return v;
            } else {                                    /* array is not allocated */
                Py_INCREF(Py_None);
                return Py_None;
            }
        }
    if (strcmp(name,"__dict__")==0) {
        Py_INCREF(fp->dict);
        return fp->dict;
    }
    if (strcmp(name,"__doc__")==0) {
        PyObject *s = PyString_FromString("");
        for (i=0;i<fp->len;i++)
            PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i]));
        if (PyDict_SetItemString(fp->dict, name, s))
            return NULL;
        return s;
    }
    if ((strcmp(name,"_cpointer")==0) && (fp->len==1)) {
        PyObject *cobj = PyCObject_FromVoidPtr((void *)(fp->defs[0].data),NULL);
        if (PyDict_SetItemString(fp->dict, name, cobj))
            return NULL;
        return cobj;
    }
    return Py_FindMethod(fortran_methods, (PyObject *)fp, name);
}
Beispiel #11
0
// post to the console
PyObject* pybase::StdOut_Write(PyObject* self, PyObject* args)
{
    // should always be a tuple
    FLEXT_ASSERT(PyTuple_Check(args));

    const int sz = PyTuple_GET_SIZE(args);

    for(int i = 0; i < sz; ++i) {
        PyObject *val = PyTuple_GET_ITEM(args,i); // borrowed reference
        PyObject *str = PyObject_Str(val); // new reference
        char *cstr = PyString_AS_STRING(str);
        char *lf = strchr(cstr,'\n');

        // line feed in string
        if(!lf) {
            // no -> just append
            if(output)
                PyString_ConcatAndDel(&output,str); // str is decrefd
            else
                output = str; // take str reference
        }
        else {
            // yes -> append up to line feed, reset output buffer to string remainder
            PyObject *part = PyString_FromStringAndSize(cstr,lf-cstr); // new reference
            if(output)
                PyString_ConcatAndDel(&output,part); // str is decrefd  
            else
                output = part; // take str reference

            // output concatenated string
            post(PyString_AS_STRING(output));

            Py_DECREF(output);
            output = PyString_FromString(lf+1);  // new reference
        }
    }

    Py_INCREF(Py_None);
    return Py_None;
}
Beispiel #12
0
static void PyString_ConcatFromString(PyObject** strPtr, char* addend) {
   PyObject* pyAddend = 0;
   
   Assert(strPtr);
   if ( !addend ) return;

   /* ----------------------------------------------- */
   /* Build a Py string from the addend               */
   /* ----------------------------------------------- */
   pyAddend = PyString_FromString(addend);
   PyString_ConcatAndDel(strPtr,pyAddend);
   pyAddend = 0;
}
Beispiel #13
0
void
pystring_concat_str(PyObject **pystr, PyObject *obj)
{
#if PY_MAJOR_VERSION >= 3
    PyObject *repr = PyObject_Str(obj);
    PyObject *newstr = PyUnicode_Concat(*pystr, repr);
    Py_DECREF(repr);
    Py_DECREF(*pystr);
    *pystr = newstr;
#else
    PyString_ConcatAndDel(pystr, PyObject_Str(obj));
#endif
}
Beispiel #14
0
void
pystring_concat(PyObject **pystr, const char *chars)
{
#if PY_MAJOR_VERSION >= 3
    PyObject *str = PyUnicode_FromString(chars);
    PyObject *newstr = PyUnicode_Concat(*pystr, str);
    Py_DECREF(str);
    Py_DECREF(*pystr);
    *pystr = newstr;
#else
    PyString_ConcatAndDel(pystr, PyString_FromString(chars));
#endif
}
static PyObject *slot_QQuaternion___repr__(PyObject *sipSelf)
{
    QQuaternion *sipCpp = reinterpret_cast<QQuaternion *>(sipGetCppPtr((sipSimpleWrapper *)sipSelf,sipType_QQuaternion));

    if (!sipCpp)
        return 0;


    {
        {
            PyObject * sipRes = 0;

#line 45 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtGui/qquaternion.sip"
        PyObject *scalar = PyFloat_FromDouble(sipCpp->scalar());
        PyObject *x = PyFloat_FromDouble(sipCpp->x());
        PyObject *y = PyFloat_FromDouble(sipCpp->y());
        PyObject *z = PyFloat_FromDouble(sipCpp->z());
        
        if (scalar && x && y && z)
        {
        #if PY_MAJOR_VERSION >= 3
            sipRes = PyUnicode_FromFormat("PyQt5.QtGui.QQuaternion(%R, %R, %R, %R)",
                    scalar, x, y, z);
        #else
            sipRes = PyString_FromString("PyQt5.QtGui.QQuaternion(");
            PyString_ConcatAndDel(&sipRes, PyObject_Repr(scalar));
            PyString_ConcatAndDel(&sipRes, PyString_FromString(", "));
            PyString_ConcatAndDel(&sipRes, PyObject_Repr(x));
            PyString_ConcatAndDel(&sipRes, PyString_FromString(", "));
            PyString_ConcatAndDel(&sipRes, PyObject_Repr(y));
            PyString_ConcatAndDel(&sipRes, PyString_FromString(", "));
            PyString_ConcatAndDel(&sipRes, PyObject_Repr(z));
            PyString_ConcatAndDel(&sipRes, PyString_FromString(")"));
        #endif
        }
        
        Py_XDECREF(scalar);
        Py_XDECREF(x);
        Py_XDECREF(y);
        Py_XDECREF(z);
#line 1111 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtGui/sipQtGuiQQuaternion.cpp"

            return sipRes;
        }
    }

    return 0;
}
// TODO: 4GB越え対応
static PyObject *data2pystr(CBZDoc *doc, DWORD begin, DWORD end)
{
	DWORD remain = end - begin; // TODO: 4GB越え対応
	PyObject *str = PyString_FromString("");
	while(remain > 0)
	{
		LPBYTE pdata = doc->QueryMapViewTama2(begin, remain);
		DWORD mappedsize = doc->GetMapRemain(begin); // TODO: 4GB越え対応
		DWORD size = min(mappedsize, remain); // TODO: 4GB越え対応
		PyObject *tstr = PyString_FromStringAndSize((const char*)pdata, size);
		PyString_ConcatAndDel(&str, tstr);
		if(str == NULL) return NULL;
		begin += size;
		remain -= size;
	}
	return str;
}
Beispiel #17
0
static PyObject * table_repr(tableobject *self)
{
    PyObject *s;
    PyObject *t = NULL;
    const apr_array_header_t *ah;
    apr_table_entry_t *elts;
    int i;

    s = PyString_FromString("{");

    ah = apr_table_elts (self->table);
    elts = (apr_table_entry_t *) ah->elts;

    i = ah->nelts;
    if (i == 0)
        PyString_ConcatAndDel(&s, PyString_FromString("}"));

    while (i--)
        if (elts[i].key)
        {
            t = PyString_FromString(elts[i].key);
            PyString_ConcatAndDel(&s, PyObject_Repr(t));
            Py_XDECREF(t);

            PyString_ConcatAndDel(&s, PyString_FromString(": "));

            if (elts[i].val) {
              t = PyString_FromString(elts[i].val);
            } else {
              t = Py_None;
              Py_INCREF(t);
            }

            PyString_ConcatAndDel(&s, PyObject_Repr(t));
            Py_XDECREF(t);

            if (i > 0)
                PyString_ConcatAndDel(&s, PyString_FromString(", "));
            else
                PyString_ConcatAndDel(&s, PyString_FromString("}"));
        }

    return s;
}
Beispiel #18
0
static PyObject *
tuplerepr(PyTupleObject *v)
{
	Py_ssize_t i, n;
	PyObject *s, *temp;
	PyObject *pieces, *result = NULL;

	n = v->ob_size;
	if (n == 0)
		return PyString_FromString("()");

	/* While not mutable, it is still possible to end up with a cycle in a
	   tuple through an object that stores itself within a tuple (and thus
	   infinitely asks for the repr of itself). This should only be
	   possible within a type. */
	i = Py_ReprEnter((PyObject *)v);
	if (i != 0) {
		return i > 0 ? PyString_FromString("(...)") : NULL;
	}

	pieces = PyTuple_New(n);
	if (pieces == NULL)
		return NULL;

	/* Do repr() on each element. */
	for (i = 0; i < n; ++i) {
		if (Py_EnterRecursiveCall(" while getting the repr of a tuple"))
			goto Done;
		s = PyObject_Repr(v->ob_item[i]);
		Py_LeaveRecursiveCall();
		if (s == NULL)
			goto Done;
		PyTuple_SET_ITEM(pieces, i, s);
	}

	/* Add "()" decorations to the first and last items. */
	assert(n > 0);
	s = PyString_FromString("(");
	if (s == NULL)
		goto Done;
	temp = PyTuple_GET_ITEM(pieces, 0);
	PyString_ConcatAndDel(&s, temp);
	PyTuple_SET_ITEM(pieces, 0, s);
	if (s == NULL)
		goto Done;

	s = PyString_FromString(n == 1 ? ",)" : ")");
	if (s == NULL)
		goto Done;
	temp = PyTuple_GET_ITEM(pieces, n-1);
	PyString_ConcatAndDel(&temp, s);
	PyTuple_SET_ITEM(pieces, n-1, temp);
	if (temp == NULL)
		goto Done;

	/* Paste them all together with ", " between. */
	s = PyString_FromString(", ");
	if (s == NULL)
		goto Done;
	result = _PyString_Join(s, pieces);
	Py_DECREF(s);	

Done:
	Py_DECREF(pieces);
	Py_ReprLeave((PyObject *)v);
	return result;
}
Beispiel #19
0
static PyObject *
attr_dir_repr(PyObject *_self)
{
	attr_dir_object *self = (attr_dir_object*)_self;
	kdump_ctx *ctx = self->kdumpfile->ctx;
	kdump_attr_iter_t iter;
	kdump_status status;
	PyObject *s, *temp;
	PyObject *colon = NULL, *pieces = NULL;
	PyObject *result = NULL;
	int res;

	status = kdump_attr_ref_iter_start(ctx, &self->baseref, &iter);
	if (status != kdump_ok) {
		PyErr_Format(exception_map(status), kdump_err_str(ctx));
		return NULL;
	}

	if (!iter.key) {
		result = PyString_FromFormat("%s({})",
					     Py_TYPE(_self)->tp_name);
		goto out;
	}

	colon = PyString_FromString(": ");
	if (!colon)
		goto out;

	pieces = PyList_New(0);
	if (!pieces)
		goto out;

	while (iter.key) {
		s = PyString_FromString(iter.key);
		if (!s)
			goto out;
		temp = attr_dir_subscript(_self, s);
		if (!temp) {
			Py_DECREF(s);
			goto out;
		}
		PyString_Concat(&s, colon);
		PyString_ConcatAndDel(&s, PyObject_Repr(temp));
		Py_DECREF(temp);
		if (!s)
			goto out;

		res = PyList_Append(pieces, s);
		Py_DECREF(s);
		if (res <0)
			goto out;

		status = kdump_attr_iter_next(ctx, &iter);
		if (status != kdump_ok) {
			PyErr_Format(exception_map(status), kdump_err_str(ctx));
			goto out;
		}
	}

	s = PyString_FromFormat("%s({", Py_TYPE(_self)->tp_name);
	if (!s)
		goto out;
	temp = PyList_GET_ITEM(pieces, 0);
	PyString_ConcatAndDel(&s, temp);
	PyList_SET_ITEM(pieces, 0, s);
	if (!s)
		goto out;

	s = PyString_FromString("})");
	if (!s)
		goto out;
	temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
	PyString_ConcatAndDel(&temp, s);
	PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
	if (!temp)
		goto out;

	s = PyString_FromString(", ");
	if (!s)
		goto out;
	result = _PyString_Join(s, pieces);
	Py_DECREF(s);

 out:
	kdump_attr_iter_end(ctx, &iter);
	Py_XDECREF(pieces);
	Py_XDECREF(colon);
	return result;
}
static PyObject *slot_QMatrix3x4___repr__(PyObject *sipSelf)
{
    QMatrix3x4 *sipCpp = reinterpret_cast<QMatrix3x4 *>(sipGetCppPtr((sipSimpleWrapper *)sipSelf,sipType_QMatrix3x4));

    if (!sipCpp)
        return 0;


    {
        {
            PyObject * sipRes = 0;

#line 360 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtGui/qgenericmatrix.sip"
        bool bad = false;
        int i;
        PyObject *m[12];
        PYQT_FLOAT data[12];

        // The raw data is in column-major order but we want row-major order.
        sipCpp->copyDataTo(data);

        for (i = 0; i < 12; ++i)
        {
            m[i] = PyFloat_FromDouble(data[i]);

            if (!m[i])
                bad = true;
        }

        if (!bad)
        {
#if PY_MAJOR_VERSION >= 3
            sipRes = PyUnicode_FromFormat("PyQt5.QtGui.QMatrix3x4("
                    "%R, %R, %R, "
                    "%R, %R, %R, "
                    "%R, %R, %R, "
                    "%R, %R, %R)",
                    m[0], m[1], m[2],
                    m[3], m[4], m[5],
                    m[6], m[7], m[8],
                    m[9], m[10], m[11]);
#else
            sipRes = PyString_FromString("PyQt5.QtGui.QMatrix3x4(");

            for (i = 0; i < 12; ++i)
            {
                if (i != 0)
                    PyString_ConcatAndDel(&sipRes, PyString_FromString(", "));

                PyString_ConcatAndDel(&sipRes, PyObject_Repr(m[i]));
            }

            PyString_ConcatAndDel(&sipRes, PyString_FromString(")"));
#endif
        }

        for (i = 0; i < 12; ++i)
            Py_XDECREF(m[i]);
#line 598 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtGui/sipQtGuiQMatrix3x4.cpp"

            return sipRes;
        }
    }

    return 0;
}
Beispiel #21
0
static PyObject *
scss_Scanner_repr(scss_Scanner *self)
{
	/* Print the last 10 tokens that have been scanned in */
	PyObject *repr, *tmp;
	Token *p_token;
	int i, start, pos;

	if (self->scanner != NULL && self->scanner->tokens_sz) {
		start = self->scanner->tokens_sz - 10;
		repr = PyString_FromString("");
		for (i = (start < 0) ? 0 : start; i < self->scanner->tokens_sz; i++) {
			p_token = &self->scanner->tokens[i];
			PyString_ConcatAndDel(&repr, PyString_FromString("\n"));
			pos = (int)(p_token->string - self->scanner->input);
			PyString_ConcatAndDel(&repr, PyString_FromFormat("  (@%d)  %s  =  ",
				pos, p_token->regex->tok));
			tmp = PyString_FromStringAndSize(p_token->string, p_token->string_sz);
			PyString_ConcatAndDel(&repr, PyObject_Repr(tmp));
			Py_XDECREF(tmp);
		}
	} else {
		repr = PyString_FromString("None");
	}

	return (PyObject *)repr;

/*
	PyObject *repr, *tmp, *tmp2;
	Token *p_token;
	char *tok;
	int i, start, first = 1, cur, max=0, pos;

	if (self->scanner != NULL && self->scanner->tokens_sz) {
		start = self->scanner->tokens_sz - 10;
		repr = PyString_FromString("");
		for (i = (start < 0) ? 0 : start; i < self->scanner->tokens_sz; i++) {
			p_token = self->scanner->tokens[i];
			PyString_ConcatAndDel(&repr, PyString_FromString("\n"));
			pos = (int)(p_token->string - self->scanner->input);
			PyString_ConcatAndDel(&repr, PyString_FromFormat("  (@%d)  %s  =  ",
				pos, p_token->regex->tok));
			tmp = PyString_FromString(p_token->string);
			PyString_ConcatAndDel(&repr, PyObject_Repr(tmp));
			Py_XDECREF(tmp);
		}

		start = self->scanner->tokens_sz - 10;
		for (i = (start < 0) ? 0 : start; i < self->scanner->tokens_sz; i++) {
			p_token = self->scanner->tokens[i];
			cur = strlen(p_token->regex->tok) * 2;
			if (cur > max) max = cur;
		}
		tok = PyMem_New(char, max + 4);
		repr = PyString_FromString("");
		for (i = (start < 0) ? 0 : start; i < self->scanner->tokens_sz; i++) {
			p_token = self->scanner->tokens[i];
			if (!first) PyString_ConcatAndDel(&repr, PyString_FromString("\n"));

			pos = (int)(p_token->string - self->scanner->input);
			if (pos < 10) PyString_ConcatAndDel(&repr, PyString_FromString(" "));
			if (pos < 100) PyString_ConcatAndDel(&repr, PyString_FromString(" "));
			if (pos < 1000) PyString_ConcatAndDel(&repr, PyString_FromString(" "));
			PyString_ConcatAndDel(&repr, PyString_FromFormat("(@%d)  ",
				pos));

			tmp = PyString_FromString(p_token->regex->tok);
			tmp2 = PyObject_Repr(tmp);
			memset(tok, ' ', max + 4);
			tok[max + 3 - PyString_Size(tmp2)] = '\0';
			PyString_ConcatAndDel(&repr, PyString_FromString(tok));
			PyString_ConcatAndDel(&repr, tmp2);
			Py_XDECREF(tmp);

			PyString_ConcatAndDel(&repr, PyString_FromString("  =  "));
			tmp = PyString_FromString(p_token->string);
			PyString_ConcatAndDel(&repr, PyObject_Repr(tmp));
			Py_XDECREF(tmp);

			first = 0;
		}
		PyMem_Del(tok);
	} else {
		repr = PyString_FromString("None");
	}

	return (PyObject *)repr;
*/
}
Beispiel #22
0
static PyObject *
fortran_getattr(PyFortranObject *fp, char *name) {
    int i,j,k,flag;
    if (fp->dict != NULL) {
        PyObject *v = PyDict_GetItemString(fp->dict, name);
        if (v != NULL) {
            Py_INCREF(v);
            return v;
        }
    }
    for (i=0,j=1;i<fp->len && (j=strcmp(name,fp->defs[i].name));i++);
    if (j==0)
        if (fp->defs[i].rank!=-1) {                   /* F90 allocatable array */
            if (fp->defs[i].func==NULL) return NULL;
            for(k=0;k<fp->defs[i].rank;++k)
                fp->defs[i].dims.d[k]=-1;
            save_def = &fp->defs[i];
            (*(fp->defs[i].func))(&fp->defs[i].rank,fp->defs[i].dims.d,set_data,&flag);
            if (flag==2)
                k = fp->defs[i].rank + 1;
            else
                k = fp->defs[i].rank;
            if (fp->defs[i].data !=NULL) {              /* array is allocated */
                PyObject *v = PyArray_New(&PyArray_Type, k, fp->defs[i].dims.d,
                                          fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY,
                                          NULL);
                if (v==NULL) return NULL;
                /* Py_INCREF(v); */
                return v;
            } else {                                    /* array is not allocated */
                Py_INCREF(Py_None);
                return Py_None;
            }
        }
    if (strcmp(name,"__dict__")==0) {
        Py_INCREF(fp->dict);
        return fp->dict;
    }
    if (strcmp(name,"__doc__")==0) {
#if PY_VERSION_HEX >= 0x03000000
        PyObject *s = PyUnicode_FromString(""), *s2, *s3;
        for (i=0;i<fp->len;i++) {
            s2 = fortran_doc(fp->defs[i]);
            s3 = PyUnicode_Concat(s, s2);
            Py_DECREF(s2);
            Py_DECREF(s);
            s = s3;
        }
#else
        PyObject *s = PyString_FromString("");
        for (i=0;i<fp->len;i++)
            PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i]));
#endif
        if (PyDict_SetItemString(fp->dict, name, s))
            return NULL;
        return s;
    }
    if ((strcmp(name,"_cpointer")==0) && (fp->len==1)) {
        PyObject *cobj = F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data),NULL);
        if (PyDict_SetItemString(fp->dict, name, cobj))
            return NULL;
        return cobj;
    }
#if PY_VERSION_HEX >= 0x03000000
    if (1) {
        PyObject *str, *ret;
        str = PyUnicode_FromString(name);
        ret = PyObject_GenericGetAttr((PyObject *)fp, str);
        Py_DECREF(str);
        return ret;
    }
#else
    return Py_FindMethod(fortran_methods, (PyObject *)fp, name);
#endif
}
Beispiel #23
0
static PyObject* PyJudyIntSet_repr(PyJudyIntSet* set)
{
	if (!set->allow_print)
		return PyString_FromFormat("<%s object at %p>", Py_TYPE(set)->tp_name, (void*)set);

	char s_buffer[32];
	PyObject* retval = 0;
	PyObject* comma_space = 0;
	PyObject* s = 0;

	if (set->s == 0)
		return PyString_FromString("JudyIntSet([])");

	if ((comma_space = PyString_FromString(", ")) == 0)
		goto cleanup;

	retval = PyString_FromString("JudyIntSet([");

	if (retval == 0)
		goto cleanup;

	JError_t JError;
	Word_t v = 0;
	Judy1First(set->s, &v, &JError);

	sprintf(s_buffer, "%llu", (unsigned long long)v);
	s = PyString_FromString(s_buffer);

	if (s == 0) {
		Py_CLEAR(retval);
		goto cleanup;
	}

	PyString_ConcatAndDel(&retval, s);

	if (retval == 0)
		goto cleanup;

	while (1) {
		int i = Judy1Next(set->s, &v, &JError);

		if (i == 0)
			break;

		PyString_Concat(&retval, comma_space);

		if (retval == 0)
			goto cleanup;

		sprintf(s_buffer, "%llu", (unsigned long long)v);
		s = PyString_FromString(s_buffer);

		if (s == 0) {
			Py_CLEAR(retval);
			goto cleanup;
		}

		PyString_ConcatAndDel(&retval, s);

		if (retval == 0)
			goto cleanup;
	}

	s = PyString_FromString("])");

	if (s == 0)
		goto cleanup;

	PyString_ConcatAndDel(&retval, s);

cleanup:

	Py_XDECREF(comma_space);

	return retval;
}
Beispiel #24
0
PyObject * Field_str ( Field * self )
{
    PyObject * pyobj,
             * string,
             * typeobj;

    if ( ! ( string = PyString_FromFormat ( "Field[" ) ) )
        return 0;

    /* Output the field name - if present */
    if ( self->field.flags & FUDGE_FIELD_HAS_NAME )
    {
        PyObject * namestr,
                 * nameobj = Field_name ( self );
        if ( ! nameobj )
            goto clear_string_and_fail;

        namestr = PyObject_Str ( nameobj );
        Py_DECREF( nameobj );
        if ( ! namestr )
            goto clear_string_and_fail;

        PyString_ConcatAndDel ( &string, namestr );
        if ( ! string )
            return 0;
    }

    /* Separator between name and ordinal */
    PyString_ConcatAndDel ( &string, PyString_FromString ( "|" ) );
    if ( ! string )
        return 0;

    /* Output the field ordinal - if present */
    if ( self->field.flags & FUDGE_FIELD_HAS_ORDINAL )
    {
        PyString_ConcatAndDel ( &string, PyString_FromFormat (
                                             "%d", self->field.ordinal ) );
        if ( ! string )
            return 0;
    }

    /* Separator between ordinal and type name */
    PyString_ConcatAndDel ( &string, PyString_FromString ( "|" ) );
    if ( ! string )
        return 0;

    /* Retrieve the type name from the lookup in the types module; if
     * unknown, display the type id */
    if ( ! ( typeobj = PyInt_FromLong ( self->field.type ) ) )
        goto clear_string_and_fail;
    pyobj = PyDict_GetItem ( s_typenamedict, typeobj );
    Py_DECREF( typeobj );
    if ( pyobj )
        PyString_Concat ( &string, pyobj );
    else
        PyString_ConcatAndDel ( &string,
                                PyString_FromFormat ( "%d", self->field.type ) );
    if ( ! string )
        return 0;

    /* Separator between type name and the value */
    PyString_ConcatAndDel ( &string, PyString_FromString ( ":" ) );
    if ( ! string )
        return 0;

    /* Output the stringized field value */
    switch ( self->field.type )
    {
        case FUDGE_TYPE_INDICATOR:
            break;

        /* For all non-byte array types, use the stringized Python value */
        case FUDGE_TYPE_BOOLEAN:
        case FUDGE_TYPE_BYTE:
        case FUDGE_TYPE_SHORT:
        case FUDGE_TYPE_INT:
        case FUDGE_TYPE_LONG:
        case FUDGE_TYPE_FLOAT:
        case FUDGE_TYPE_DOUBLE:
        case FUDGE_TYPE_SHORT_ARRAY:
        case FUDGE_TYPE_INT_ARRAY:
        case FUDGE_TYPE_LONG_ARRAY:
        case FUDGE_TYPE_FLOAT_ARRAY:
        case FUDGE_TYPE_DOUBLE_ARRAY:
        case FUDGE_TYPE_STRING:
        case FUDGE_TYPE_FUDGE_MSG:
        case FUDGE_TYPE_DATE:
        case FUDGE_TYPE_TIME:
        case FUDGE_TYPE_DATETIME:
            if ( ! ( pyobj = Field_value ( self ) ) )
                goto clear_string_and_fail;
            PyString_ConcatAndDel ( &string, PyObject_Str ( pyobj ) );
            Py_DECREF( pyobj );
            break;

        /* Assume everything else is just a bundle of (potentially
         * unprintable) bytes */
        default:
            PyString_ConcatAndDel ( &string,
                                    PyString_FromFormat ( "<%d bytes>",
                                                          self->field.numbytes ) );
            break;
    }

    if ( string )
        PyString_ConcatAndDel ( &string, PyString_FromString ( "]" ) );
    return string;

clear_string_and_fail:
    Py_XDECREF( string );
    return 0;
}
Beispiel #25
0
static PyObject *finfo_repr(finfoobject *self)
{
    PyObject *s = PyString_FromString("{");
    PyObject *t = NULL;

    PyString_ConcatAndDel(&s, PyString_FromString("'fname': "));
    t = finfo_getattr(self, "fname");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'filetype': "));
    t = finfo_getattr(self, "filetype");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'valid': "));
    t = finfo_getattr(self, "valid");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'protection': "));
    t = finfo_getattr(self, "protection");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'user': "******"user");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'group': "));
    t = finfo_getattr(self, "group");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'size': "));
    t = finfo_getattr(self, "size");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'inode': "));
    t = finfo_getattr(self, "inode");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'device': "));
    t = finfo_getattr(self, "device");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'nlink': "));
    t = finfo_getattr(self, "nlink");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'atime': "));
    t = finfo_getattr(self, "atime");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'mtime': "));
    t = finfo_getattr(self, "mtime");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'ctime': "));
    t = finfo_getattr(self, "ctime");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString(", 'name': "));
    t = finfo_getattr(self, "name");
    PyString_ConcatAndDel(&s, PyObject_Repr(t));
    Py_XDECREF(t);

    PyString_ConcatAndDel(&s, PyString_FromString("}"));

    return s;
}
Beispiel #26
0
/* callback to pass to DODRC; calls the Python function in the global structure |odr_global| */
void fcn_callback(int *n, int *m, int *np, int *nq, int *ldn, int *ldm,
                  int *ldnp, double *beta, double *xplusd, int *ifixb,
                  int *ifixx, int *ldfix, int *ideval, double *f,
                  double *fjacb, double *fjacd, int *istop)
{
  PyObject *arg01, *arglist;
  PyObject *result;
  PyArrayObject *result_array = NULL;
  PyArrayObject *pyXplusD;

  arg01 = PyTuple_New(2);

  if (*m != 1)
    {
      npy_intp dim2[2];
      dim2[0] = *m;
      dim2[1] = *n;
      pyXplusD = (PyArrayObject *) PyArray_SimpleNew(2, dim2, NPY_DOUBLE);
      memcpy(pyXplusD->data, (void *)xplusd, (*m) * (*n) * sizeof(double));
    }
  else
    {
      npy_intp dim1[1];
      dim1[0] = *n;
      pyXplusD = (PyArrayObject *) PyArray_SimpleNew(1, dim1, NPY_DOUBLE);
      memcpy(pyXplusD->data, (void *)xplusd, (*n) * sizeof(double));
    }

  PyTuple_SetItem(arg01, 0, odr_global.pyBeta);
  Py_INCREF(odr_global.pyBeta);
  PyTuple_SetItem(arg01, 1, (PyObject *) pyXplusD);
  Py_INCREF((PyObject *) pyXplusD);

  if (odr_global.extra_args != NULL)
    {
      arglist = PySequence_Concat(arg01, odr_global.extra_args);
    }
  else
    {
      arglist = PySequence_Tuple(arg01);        /* make a copy */
    }

  Py_DECREF(arg01);
  *istop = 0;

  memcpy(((PyArrayObject *) (odr_global.pyBeta))->data, (void *)beta,
         (*np) * sizeof(double));

  if ((*ideval % 10) >= 1)
    {
      /* compute f with odr_global.fcn */

      if (odr_global.fcn == NULL)
        {
          /* we don't have a function to call */
          PYERR2(odr_error, "Function has not been initialized");
        }

      if ((result = PyEval_CallObject(odr_global.fcn, arglist)) == NULL)
        {
          PyObject *tmpobj, *str1;

          if (PyErr_ExceptionMatches(odr_stop))
            {
              /* stop, don't fail */
              *istop = 1;

              Py_DECREF(arglist);
              return;
            }

          PyErr_Print();
          tmpobj = PyObject_GetAttrString(odr_global.fcn, "func_name");
          if (tmpobj == NULL)
            goto fail;

          str1 =
            PyString_FromString
            ("Error occurred while calling the Python function named ");
          if (str1 == NULL)
            {
              Py_DECREF(tmpobj);
              goto fail;
            }
          PyString_ConcatAndDel(&str1, tmpobj);
          PyErr_SetString(odr_error, PyString_AsString(str1));
          Py_DECREF(str1);
          goto fail;
        }

      if ((result_array =
           (PyArrayObject *) PyArray_ContiguousFromObject(result,
                                                          NPY_DOUBLE, 0,
                                                          2)) == NULL)
        {
          PYERR2(odr_error,
                 "Result from function call is not a proper array of floats.");
        }

      memcpy((void *)f, result_array->data, (*n) * (*nq) * sizeof(double));
      Py_DECREF(result_array);
    }

  if (((*ideval) / 10) % 10 >= 1)
    {
      /* compute fjacb with odr_global.fjacb */

      if (odr_global.fjacb == NULL)
        {
          /* we don't have a function to call */
          PYERR2(odr_error, "Function has not been initialized");
        }

      if ((result = PyEval_CallObject(odr_global.fjacb, arglist)) == NULL)
        {
          PyObject *tmpobj, *str1;

          if (PyErr_ExceptionMatches(odr_stop))
            {
              /* stop, don't fail */
              *istop = 1;

              Py_DECREF(arglist);
              return;
            }

          PyErr_Print();
          tmpobj = PyObject_GetAttrString(odr_global.fjacb, "func_name");
          if (tmpobj == NULL)
            goto fail;

          str1 =
            PyString_FromString
            ("Error occurred while calling the Python function named ");
          if (str1 == NULL)
            {
              Py_DECREF(tmpobj);
              goto fail;
            }
          PyString_ConcatAndDel(&str1, tmpobj);
          PyErr_SetString(odr_error, PyString_AsString(str1));
          Py_DECREF(str1);
          goto fail;
        }

      if ((result_array =
           (PyArrayObject *) PyArray_ContiguousFromObject(result,
                                                          NPY_DOUBLE, 0,
                                                          2)) == NULL)
        {
          PYERR2(odr_error,
                 "Result from function call is not a proper array of floats.");
        }

      if (*nq != 1 && *np != 1)
        {
          /* result_array should be rank-3 */

          if (result_array->nd != 3)
            {
              Py_DECREF(result_array);
              PYERR2(odr_error, "Beta Jacobian is not rank-3");
            }
        }
      else if (*nq == 1)
        {
          /* result_array should be rank-2 */

          if (result_array->nd != 2)
            {
              Py_DECREF(result_array);
              PYERR2(odr_error, "Beta Jacobian is not rank-2");
            }
        }

      memcpy((void *)fjacb, result_array->data,
             (*n) * (*nq) * (*np) * sizeof(double));
      Py_DECREF(result_array);

    }

  if (((*ideval) / 100) % 10 >= 1)
    {
      /* compute fjacd with odr_global.fjacd */

      if (odr_global.fjacd == NULL)
        {
          /* we don't have a function to call */
          PYERR2(odr_error, "fjcad has not been initialized");
        }

      if ((result = PyEval_CallObject(odr_global.fjacd, arglist)) == NULL)
        {
          PyObject *tmpobj, *str1;

          if (PyErr_ExceptionMatches(odr_stop))
            {
              /* stop, don't fail */
              *istop = 1;

              Py_DECREF(arglist);
              return;
            }

          PyErr_Print();
          tmpobj = PyObject_GetAttrString(odr_global.fjacd, "func_name");
          if (tmpobj == NULL)
            goto fail;

          str1 =
            PyString_FromString
            ("Error occurred while calling the Python function named ");
          if (str1 == NULL)
            {
              Py_DECREF(tmpobj);
              goto fail;
            }
          PyString_ConcatAndDel(&str1, tmpobj);
          PyErr_SetString(odr_error, PyString_AsString(str1));
          Py_DECREF(str1);
          goto fail;
        }

      if ((result_array =
           (PyArrayObject *) PyArray_ContiguousFromObject(result,
                                                          NPY_DOUBLE, 0,
                                                          2)) == NULL)
        {
          PYERR2(odr_error,
                 "Result from function call is not a proper array of floats.");
        }

      if (*nq != 1 && *m != 1)
        {
          /* result_array should be rank-3 */

          if (result_array->nd != 3)
            {
              Py_DECREF(result_array);
              PYERR2(odr_error, "xplusd Jacobian is not rank-3");
            }
        }
      else if (*nq == 1 && *m != 1)
        {
          /* result_array should be rank-2 */

          if (result_array->nd != 2)
            {
              Py_DECREF(result_array);
              PYERR2(odr_error, "xplusd Jacobian is not rank-2");
            }
        }
      else if (*nq == 1 && *m == 1)
        {
          /* result_array should be rank-1 */

          if (result_array->nd != 1)
            {
              Py_DECREF(result_array);
              PYERR2(odr_error, "xplusd Jacobian is not rank-1");
            }
        }

      memcpy((void *)fjacd, result_array->data,
             (*n) * (*nq) * (*m) * sizeof(double));
      Py_DECREF(result_array);
    }

  Py_DECREF(result);
  Py_DECREF(arglist);
  Py_DECREF(pyXplusD);

  return;

fail:
  Py_XDECREF(result);
  Py_XDECREF(arglist);
  Py_XDECREF(pyXplusD);
  *istop = -1;
  return;
}
Beispiel #27
0
static PyObject *
get_mac_address(PyObject *self, PyObject *args)
{
  int s;
  struct sockaddr_ll sll;
  struct ifreq ifr;
  int i;
  char *adapter;
  char hex[8];
  PyObject *result;

  // >>> get_mac_address(adapter_name)
  if (!PyArg_ParseTuple(args, "s", &adapter)) {
    return NULL;
  }
  s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_802_2));
  if (s < 0) {
    if (errno == EPERM) {
      args = PyTuple_New(3);
      PyTuple_SetItem(args, 0, PyInt_FromLong(EPERM));
      PyTuple_SetItem(args, 1, PyString_FromString(strerror(EPERM)));
      PyTuple_SetItem(args, 2, PyString_FromString(adapter));
      set_mpx_exception("EPermission", args, NULL);
      return NULL;
    }
    goto raise_os_error;
  }
  // Find the interface's index.
  memset(&ifr, 0, sizeof(ifr));
  strncpy(ifr.ifr_name, adapter, sizeof(ifr.ifr_name));

  if (ioctl(s, SIOCGIFINDEX, &ifr) == -1) {
    if (errno == ENODEV) {
      args = PyTuple_New(1); 
      PyTuple_SetItem(args, 0, PyString_FromString(adapter));
      set_mpx_exception("ENoSuchName", args, NULL);
      return NULL;
    }
    goto raise_os_error;
  }

  // Use the interface's index to bind the socket.
  memset(&sll, 0, sizeof(sll));
  sll.sll_family          = AF_PACKET;
  sll.sll_ifindex         = ifr.ifr_ifindex;
  sll.sll_protocol        = htons(ETH_P_ALL);

  if (bind(s, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
    goto raise_os_error;
  }
  // Find the MAC address of the interface and set addr accordingly.
  memset(&ifr, 0, sizeof(ifr));
  strncpy(ifr.ifr_name, adapter, sizeof(ifr.ifr_name));

  if (ioctl(s, SIOCGIFHWADDR, &ifr) == -1) {
    goto raise_os_error;
  }
  // There's probably a more efficient way to do this...
  result = PyString_FromString("");
  for (i=0; i<6; i++) {
    sprintf(hex, "%02x", (unsigned char)ifr.ifr_ifru.ifru_hwaddr.sa_data[i]);
    PyString_ConcatAndDel(&result, PyString_FromString(hex));
  }
  return result;
 raise_os_error:
  PyErr_SetFromErrno(PyExc_OSError);
  if (s > -1) {
    close(s);
  }
  return NULL;
}