Linux/Unix > Python Essential Reference, Second Edition > B. Extending and Embedding Python > Converting Data from Python to C | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105095080112008053028057

### Converting Data from Python to C

The following functions are used to convert arguments passed from Python to C.

    int PyArg_ParseTuple(PyObject * args, char * format, ...);

Parses a tuple of objects in `args` into a series of C variables. `format` is a format string containing zero or more of the specifier strings from Table B.1, which describes the expected contents of `args` . All the remaining arguments contain the addresses of C variables into which the results will be placed. The order and types of these arguments must match the specifiers used in `format` and use the C datatypes listed in Table B.1. Zero is returned if the arguments could not be parsed.

    int PyArg_ParseTupleAndKeywords(PyObject * args, PyObject * kwdict,
                                    char * format, char ** kwlist, ...);

Parses both a tuple of arguments and a dictionary containing keyword arguments contained in `kwdict` . `format` has the same meaning as for `PyArg_ParseTuple()`. The only difference is that `kwlist` is a null-terminated list of strings containing the names of all the arguments. Returns `1` on success, `0` on error.

Note: In Table B.1, results of a conversion (for example, in `char *``r` or `char **``r` ) are always placed in the parameter labeled `r` . When applicable, a length is stored in `len` .

##### Table B.1. Base Format Specifiers and Associated C Datatypes for `PyArg_Parse*`

Format | Python Type | C Type
--- | --- | ---
`"s"` | String or Unicode | `char **``r`
`"s#"` | String or Unicode | `char **``r` `, int *``len`
`"z"` | String, Unicode, or None | `char **``r`
`"z#"` | String, Unicode, or None | `char **r, int *``len`
`"u"` | Unicode | `Py_UNICODE **``r`
`"u#"` | Unicode | `Py_UNICODE **``r` `, int *``len`
`"es"` | String, Unicode, or buffer | `const char *``enc` `, char **``r`
`"es#"` | String, Unicode, or buffer | `const char *``enc` `, char **``r` `, int *``len`
`"b"` | Integer | `char *``r`
`"h"` | Integer | `short *``r`
`"i"` | Integer | `int *``r`
`"l"` | Integer | `long int *``r`
`"c"` | String of length 1 | `char *``r`
`"f"` | Float | `float *``r`
`"d"` | Float | `double *``r`
`"D"` | Complex | `Py_complex *``r`
`"O"` | Any | `PyObject **``r`
`"O!"` | Any | `PyTypeObject *``type` `, PyObject **``r`
`"O&"` | Any | `int (*``converter` `)(PyObject *, void *), void *``r`
`"S"` | String | `PyObject **``r`
`"U"` | Unicode | `PyObject **``r`
`"t#'` | Read-only buffer | `char **``r` `, int *``len`
`"w"` | Read-write buffer | `char **``r`
`"w#"` | Read-write buffer | `char **``r` `, int *``len`

When converting integer values, an `OverflowError` exception is raised if the Python integer is too large to fit into the requested C datatype. Long integers may also be used anyplace an integer is expected, provided that they’re small enough to fit.

When converting strings with the `"s"`, `"s#"`, `"z"`, or `"z#"` specifiers, both standard and Unicode strings may be used. The `"z"` specifiers also allow `None` to be passed, in which case a `NULL` pointer is returned. In both cases, it’s unnecessary to allocate space for the returned string—a pointer to the raw string data stored in the Python interpreter is returned. When Unicode strings are passed, they’re first converted to an 8-bit string using the default Unicode encoding. The `"u"` and `"u#"` specifiers require a Unicode string and return a pointer to raw Unicode string data, where each character is of type `Py_UNICODE` (which is currently the same as the C `wchar_t` type). The `"s#"`, `"z#"`, and `"u#"` specifiers return the string length in addition to the string data.

The `"es"` and `"es#"` specifiers are used to read a string or Unicode string that has been encoded according to a specific encoding rule. For example:

    char *buffer;
    PyArg_ParseTuple(args,"es","utf-8",&buffer);

In this case, `PyArg_ParseTuple()` first reads an encoding name and then returns a pointer to a buffer in which an encoded version of the string has been placed. This buffer contains dynamically allocated memory and must be explicitly deallocated using `PyMem_Free()` after the caller has finished using the encoded contents. The `"es#"` specifier optionally accepts a buffer length. In this case, a user can pass the address and length of a preallocated buffer in which encoded string data will be placed. The `len` parameter is always set to the actual length of the encoded data upon return.

The `"t#"`, `"w"`, and `"w#"` specifiers are similar to the string-conversion specifiers, but return a pointer to byte-oriented data stored in a Python object implementing the buffer interface. String and Unicode objects provide this interface, as do selected types in the standard library, such as arrays created with the `array` module and `mmap` objects created by the `mmap` module.

The `"O"`, `"S"`, and `"U"` specifiers return raw Python objects of type `PyObject *`. `"S"` and `"U"` restrict this object to be a string or Unicode string, respectively.

The `"O!"` conversion requires two C arguments: a pointer to a Python type object and a pointer to a `PyObject *` into which a pointer to the object is placed. A `TypeError` is raised if the type of the object doesn’t match the type object. For example:

    /* Parse a List Argument */
    PyObject *listobj1;
    PyArg_ParseTuple(args,"O!", &PyList_Type, &listobj1);

The `"O&"` conversion takes two arguments (`converter` `,` `addr` ) and uses a function to convert a `PyObject *` to a C datatype. `converter` is a pointer to a function with the prototype `int` `converter` `(PyObject *``obj` `, void *``addr` `)`, where `obj` is the passed Python object, and `addr` is the address supplied as the second argument. `converter` `()` should return `1` on success, `0` on failure. On error, the converter should also raise an exception. For example:

    struct Point {
         int x;
         int y;
    };

    int convert_point(PyObject *obj, void *addr) {
        Point *p = (Point *) addr;
        return PyArg_ParseTuple(obj,"ii", &p->x, &p->y);
    }
    ...
    PyObject *wrapper(PyObject *self, PyObject *args) {
        Point p;
        ...
        /* Get a point */
        if (!PyArg_ParseTuple(args,'O&",convert_point, &p))
            return NULL;
        ...
    }

Table B.2 lists format modifiers that can also be used in format strings.

##### Table B.2. Format String Modifiers

Format String | Description
--- | ---
`"(``items` `)"` | A tuple of objects
`"|"` | Start of optional arguments
`":"` | End of arguments (the remaining text is the function name)
`";"` | End of arguments (the remaining text is the error message)

`"|"` specifies that all remaining arguments are optional. This can appear only once in a format specifier and cannot be nested. `":"` indicates the end of the arguments. Any text that follows is used as the function name in any error messages. `";"` signals the end of the arguments. Any following text is used as the error message. Note: Only one of `:` and `;` should be used. Listing B.2 shows some examples:

##### Listing B.2 Format Specifiers

    int       ival, ival2, len;
    double    dval;
    char     *sval;
    PyObject *o1, *o2;

    /* Parse an integer, double, and a string */
    PyArg_ParseTuple(args,"ids", &ival, &dval, &sval);

    /* Parse a string and length */
    PyArg_ParseTuple(args,"s#", &sval, &len);

    /* Parse optional arguments */
    PyArg_ParseTuple(args,"id|s", &ival, &dval, &sval);

    /* Parse with an error message */
    PyArg_ParseTuple(args,"ii; gcd requires 2 integers", &ival, &ival2);

    /* Parse two tuples */
    PyArg_ParseTuple(args,"(ii)(ds)", &ival, &ival2, &dval, &sval);

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.