跳转到主要内容

Expat C API

The xml.parsers.expat module exposes selected Expat functions through its expat_CAPI capsule. This allows extension modules to use the same Expat library as Python. The interface is declared in pyexpat.h, which is not included by Python.h and must be included after Expat's expat.h header.

To use the C API, add the following code to the extension module initialization function and store the pointer to the C API in the module state:

struct PyExpat_CAPI *capi = NULL;
capi = (struct PyExpat_CAPI *)PyCapsule_Import(PyExpat_CAPSULE_NAME, 0);
if (capi == NULL) {
    goto error;
}
if (!(
     strcmp(capi->magic, PyExpat_CAPI_MAGIC) == 0
     && (size_t)capi->size >= sizeof(struct PyExpat_CAPI)
)) {
    PyErr_SetString(PyExc_ImportError, "pyexpat version is incompatible");
    goto error;
}

The name of the capsule containing the Expat C API: "pyexpat.expat_CAPI". Pass this to PyCapsule_Import to obtain a pointer to a PyExpat_CAPI.

The string identifying the layout of PyExpat_CAPI. Before using the function pointers in the structure, check that its magic member compares equal to this string using strcmp() and its size member is at least sizeof(struct PyExpat_CAPI).

Table of function pointers exported by xml.parsers.expat. The capsule owns this structure: treat it as read-only and do not free it. Keep a strong reference to the capsule while using the table.

Check the compatibility fields as described under PyExpat_CAPI_MAGIC before using the function pointers.

Interface identifier, set to PyExpat_CAPI_MAGIC.

Size of the structure in bytes, set to sizeof(struct PyExpat_CAPI) by the xml.parsers.expat module that created the capsule.

Pointer to XML_SetUnknownEncodingHandler. The handler may set a Python exception on failure. The caller must check for a Python exception after parsing.

Python's unknown-encoding handler for Expat, used with XML_SetUnknownEncodingHandler. It uses Python's codec registry to fill info. The encodingHandlerData argument is unused. Calling this handler requires an attached thread state.

3.3

Pointers to the corresponding Expat functions, or NULL if not available in the Expat version used by xml.parsers.expat, are listed below.

Member names omit the XML_ prefix; for example, SetHashSalt exposes Expat's XML_SetHashSalt function. See the Expat API reference for their behavior.

3.2

3.3

Might be NULL for Expat versions prior to 2.1.0.

3.4

Might be NULL for Expat versions prior to 2.6.0.

3.8

Might be NULL for Expat versions prior to 2.7.2.

3.10

Might be NULL for Expat versions prior to 2.7.2.

3.10

Might be NULL for Expat versions prior to 2.4.0.

3.10

Might be NULL for Expat versions prior to 2.4.0.

3.10

Might be NULL for Expat versions prior to 2.8.0.

3.16