My first Python extension

Kragen Sitaker kragen at dnaco.net
Fri Mar 17 07:55:28 EST 2000


Here's my first Python module written in C.  (This is considerably
easier than writing Perl extensions in C.)  I have a few questions.

Did I do the memory management on the returned object correctly?  I
think Py_BuildValue is handing me a reference, and that after the
caller e.g. stores the returned PyObject in a Python variable, the
returned object will have exactly one reference to it.

It looks like Py_BuildValue("s#") does indeed allocate its own buffer
for the string and copy the string into that buffer.  Is there a way to
avoid this?  It might not be the most desirable method.

(I know I should be handling malloc failure.  :)

static PyObject *
judith_xorstrings(PyObject *self, PyObject *args)
{
        char *string1, *string2;
        char *outstring;
        int len1, len2, outlen, i;
        PyObject *rv = NULL;

        if (!PyArg_ParseTuple(args, "s#s#:judith.xorstrings", 
                                &string1, &len1, &string2, &len2)) {
                return NULL;
        }
        outlen = (len1 < len2) ? len1 : len2;

        outstring = malloc(outlen+1);

        /* not the quickest way to do it, but the simplest */
        for (i = 0; i != outlen; i++) {
                outstring[i] = string1[i] ^ string2[i];
        }

        /* I can't find the answers to these questions in the docs in 
         * 'ext' or 'api' from Python 1.5.2:
         * - does Py_BuildValue copy outstring, or does it create a string
         *   object containing a reference to it?
         * - if the latter, how should I allocate outstring?
         * I'm assuming the answers are "it copies" and "it doesn't matter as
         * long as you free it."
         */
        rv = Py_BuildValue("s#", outstring, outlen);

        strncpy(outstring, "WRONG", outlen);
        free(outstring);

        if (!rv) {
                return NULL;
        }

        return rv;
}

static PyMethodDef judith_methods[] = {
        {"xorstrings", judith_xorstrings, METH_VARARGS},
        {NULL, NULL}
};

void initjudith() 
{
        (void)Py_InitModule("judith", judith_methods);
}

-- 
<kragen at pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
The Internet stock bubble didn't burst on 1999-11-08.  Hurrah!
<URL:http://www.pobox.com/~kragen/bubble.html>
The power didn't go out on 2000-01-01 either.  :)



More information about the Python-list mailing list