Source

sphinx / Doc-26 / c-api / utilities.rst

Full commit

Utilities

The functions in this chapter perform various utility tasks, ranging from helping C code be more portable across platforms, using Python modules from C, and parsing function arguments and constructing Python values from C values.

Operating System Utilities

Process Control

Importing Modules

Data marshalling support

These routines allow C code to work with serialized objects using the same data format as the :mod:`marshal` module. There are functions to write data into the serialization format, and additional functions that can be used to read the data back. Files used to store marshalled data must be opened in binary mode.

Numeric values are stored with the least significant byte first.

The module supports two versions of the data format: version 0 is the historical version, version 1 (new in Python 2.4) shares interned strings in the file, and upon unmarshalling. Py_MARSHAL_VERSION indicates the current file format (currently 1).

The following functions allow marshalled values to be read back in.

XXX What about error detection? It appears that reading past the end of the file will always result in a negative numeric value (where that's relevant), but it's not clear that negative values won't be handled properly when there's no error. What's the right way to tell? Should only non-negative values be written using these routines?

Parsing arguments and building values

These functions are useful when creating your own extensions functions and methods. Additional information and examples are available in Extending and Embedding the Python Interpreter (XXX reference: ../ext/ext.html).

The first three of these functions described, :cfunc:`PyArg_ParseTuple`, :cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`PyArg_Parse`, all use format strings which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions.

A format string consists of zero or more "format units." A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed.

s (string or Unicode object) [const char *]
Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded NUL bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are converted to C strings using the default encoding. If this conversion fails, a :exc:`UnicodeError` is raised.
s# (string, Unicode or any read buffer compatible object) [const char *, int]
This variant on s stores into two C variables, the first one a pointer to a character string, the second one its length. In this case the Python string may contain embedded null bytes. Unicode objects pass back a pointer to the default encoded string version of the object if such a conversion is possible. All other read-buffer compatible objects pass back a reference to the raw internal data representation.
z (string or None) [const char *]
Like s, but the Python object may also be None, in which case the C pointer is set to NULL.
z# (string or None or any read buffer compatible object) [const char *, int]
This is to s# as z is to s.
u (Unicode object) [Py_UNICODE *]
Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of 16-bit Unicode (UTF-16) data. As with s, there is no need to provide storage for the Unicode data buffer; a pointer to the existing Unicode data is stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass.
u# (Unicode object) [Py_UNICODE *, int]
This variant on u stores into two C variables, the first one a pointer to a Unicode data buffer, the second one its length. Non-Unicode objects are handled by interpreting their read-buffer pointer as pointer to a :ctype:`Py_UNICODE` array.
es (string, Unicode object or character buffer compatible object) [const char *encoding, char **buffer]

This variant on s is used for encoding Unicode and objects convertible to Unicode into a character buffer. It only works for encoded data without embedded NUL bytes.

This format requires two arguments. The first is only used as input, and must be a :ctype:`const char\*` which points to the name of an encoding as a NUL- terminated string, or NULL, in which case the default encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a :ctype:`char\*\*`; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument.

:cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust *buffer to reference the newly allocated storage. The caller is responsible for calling :cfunc:`PyMem_Free` to free the allocated buffer after use.

et (string, Unicode object or character buffer compatible object) [const char *encoding, char **buffer]
Same as es except that 8-bit string objects are passed through without recoding them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter.
es# (string, Unicode object or character buffer compatible object) [const char *encoding, char **buffer, int *buffer_length]

This variant on s# is used for encoding Unicode and objects convertible to Unicode into a character buffer. Unlike the es format, this variant allows input data which contains NUL characters.

It requires three arguments. The first is only used as input, and must be a :ctype:`const char\*` which points to the name of an encoding as a NUL- terminated string, or NULL, in which case the default encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a :ctype:`char\*\*`; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer will be set to the number of bytes in the output buffer.

There are two modes of operation:

If *buffer points a NULL pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set *buffer to reference the newly allocated storage. The caller is responsible for calling :cfunc:`PyMem_Free` to free the allocated buffer after usage.

If *buffer points to a non-NULL pointer (an already allocated buffer), :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the initial value of *buffer_length as the buffer size. It will then copy the encoded data into the buffer and NUL-terminate it. If the buffer is not large enough, a :exc:`ValueError` will be set.

In both cases, *buffer_length is set to the length of the encoded data without the trailing NUL byte.

et# (string, Unicode object or character buffer compatible object) [const char *encoding, char **buffer]
Same as es# except that string objects are passed through without recoding them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter.
b (integer) [char]
Convert a Python integer to a tiny int, stored in a C :ctype:`char`.
B (integer) [unsigned char]
Convert a Python integer to a tiny int without overflow checking, stored in a C :ctype:`unsigned char`.
h (integer) [short int]
Convert a Python integer to a C :ctype:`short int`.
H (integer) [unsigned short int]
Convert a Python integer to a C :ctype:`unsigned short int`, without overflow checking.
i (integer) [int]
Convert a Python integer to a plain C :ctype:`int`.
I (integer) [unsigned int]
Convert a Python integer to a C :ctype:`unsigned int`, without overflow checking.
l (integer) [long int]
Convert a Python integer to a C :ctype:`long int`.
k (integer) [unsigned long]
Convert a Python integer or long integer to a C :ctype:`unsigned long` without overflow checking.
L (integer) [PY_LONG_LONG]
Convert a Python integer to a C :ctype:`long long`. This format is only available on platforms that support :ctype:`long long` (or :ctype:`_int64` on Windows).
K (integer) [unsigned PY_LONG_LONG]
Convert a Python integer or long integer to a C :ctype:`unsigned long long` without overflow checking. This format is only available on platforms that support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows).
n (integer) [Py_ssize_t]
Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`.
c (string of length 1) [char]
Convert a Python character, represented as a string of length 1, to a C :ctype:`char`.
f (float) [float]
Convert a Python floating point number to a C :ctype:`float`.
d (float) [double]
Convert a Python floating point number to a C :ctype:`double`.
D (complex) [Py_complex]
Convert a Python complex number to a C :ctype:`Py_complex` structure.
O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference count is not increased. The pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type :ctype:`PyObject\*`) into which the object pointer is stored. If the Python object does not have the required type, :exc:`TypeError` is raised.
O& (object) [converter, anything]

Convert a Python object to a C variable through a converter function. This takes two arguments: the first is a function, the second is the address of a C variable (of arbitrary type), converted to :ctype:`void \*`. The converter function in turn is called as follows:

status = converter(object, address);

where object is the Python object to be converted and address is the :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function. The returned status should be 1 for a successful conversion and 0 if the conversion has failed. When the conversion fails, the converter function should raise an exception.

S (string) [PyStringObject *]
Like O but requires that the Python object is a string object. Raises :exc:`TypeError` if the object is not a string object. The C variable may also be declared as :ctype:`PyObject\*`.
U (Unicode string) [PyUnicodeObject *]
Like O but requires that the Python object is a Unicode object. Raises :exc:`TypeError` if the object is not a Unicode object. The C variable may also be declared as :ctype:`PyObject\*`.
t# (read-only character buffer) [char *, int]
Like s#, but accepts any object which implements the read-only buffer interface. The :ctype:`char\*` variable is set to point to the first byte of the buffer, and the :ctype:`int` is set to the length of the buffer. Only single-segment buffer objects are accepted; :exc:`TypeError` is raised for all others.
w (read-write character buffer) [char *]
Similar to s, but accepts any object which implements the read-write buffer interface. The caller must determine the length of the buffer by other means, or use w# instead. Only single-segment buffer objects are accepted; :exc:`TypeError` is raised for all others.
w# (read-write character buffer) [char *, int]
Like s#, but accepts any object which implements the read-write buffer interface. The :ctype:`char \*` variable is set to point to the first byte of the buffer, and the :ctype:`int` is set to the length of the buffer. Only single-segment buffer objects are accepted; :exc:`TypeError` is raised for all others.
(items) (tuple) [matching-items]

The object must be a Python sequence whose length is the number of format units in items. The C arguments must correspond to the individual format units in items. Format units for sequences may be nested.

Note

Prior to Python version 1.5.2, this format specifier only accepted a tuple containing the individual parameters, not an arbitrary sequence. Code which previously caused :exc:`TypeError` to be raised here may now proceed without an exception. This is not expected to be a problem for existing code.

It is possible to pass Python long integers where integers are requested; however no proper range checking is done --- the most significant bits are silently truncated when the receiving field is too small to receive the value (actually, the semantics are inherited from downcasts in C --- your mileage may vary).

A few other characters have a meaning in a format string. These may not occur inside nested parentheses. They are:

|
Indicates that the remaining arguments in the Python argument list are optional. The C variables corresponding to optional arguments should be initialized to their default value --- when an optional argument is not specified, :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C variable(s).
:
The list of format units ends here; the string after the colon is used as the function name in error messages (the "associated value" of the exception that :cfunc:`PyArg_ParseTuple` raises).
;
The list of format units ends here; the string after the semicolon is used as the error message instead of the default error message. Clearly, : and ; mutually exclude each other.

Note that any Python object references which are provided to the caller are borrowed references; do not decrement their reference count!

Additional arguments passed to these functions must be addresses of variables whose type is determined by the format string; these are used to store values from the input tuple. There are a few cases, as described in the list of format units above, where these parameters are used as input values; they should match what is specified for the corresponding format unit in that case.

For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions return true, otherwise they return false and raise an appropriate exception.

String conversion and formatting

Functions for number conversion and formatted string output.

:cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` wrap the Standard C library functions :cfunc:`snprintf` and :cfunc:`vsnprintf`. Their purpose is to guarantee consistent behavior in corner cases, which the Standard C functions do not.

The wrappers ensure that str*[*size-1] is always '\\0' upon return. They never write more than size bytes (including the trailing '\\0' into str. Both functions require that str != NULL, size > 0 and format != NULL.

If the platform doesn't have :cfunc:`vsnprintf` and the buffer size needed to avoid truncation exceeds size by more than 512 bytes, Python aborts with a Py_FatalError.

The return value (rv) for these functions should be interpreted as follows:

  • When 0 <= rv < size, the output conversion was successful and rv characters were written to str (excluding the trailing '\\0' byte at str*[*rv]).
  • When rv >= size, the output conversion was truncated and a buffer with rv + 1 bytes would have been needed to succeed. str*[*size-1] is '\\0' in this case.
  • When rv < 0, "something bad happened." str*[*size-1] is '\\0' in this case too, but the rest of str is undefined. The exact cause of the error depends on the underlying platform.

The following functions provide locale-independent string to number conversions.