数据 marshal 操作支持

这些例程允许 C 代码处理与 marshal 模块所用相同数据格式的序列化对象。 其中有些函数可用来将数据写入这种序列化格式,另一些函数则可用来读取并恢复数据。用于存储 marshal 数据的文件必须以二进制模式打开。

数字值在存储时会将最低位字节放在开头。

该模块支持多种版本的数据格式;请参阅 Python 模块文档 了解详情。

The following exceptions can be raised by these functions: ValueError if the value cannot be marshalled, ValueError or TypeError if the data is malformed, EOFError if the end of the data is reached before the value is complete, OSError if reading from or writing to a FILE* fails, KeyboardInterrupt if reading or writing is interrupted by a signal, and MemoryError if memory allocation fails.

在 3.16.0a0 (unreleased) 版本发生变更: Previously, in functions taking a FILE*, the reading functions raised EOFError instead of OSError and KeyboardInterrupt, and the writing functions ignored I/O errors and interruptions.

Py_MARSHAL_VERSION

当前格式版本。参见 marshal.version

void PyMarshal_WriteLongToFile(long value, FILE *file, int version)

将一个 long 整数 value 以 marshal 格式写入 file。这将只写入 value 中最低的 32 个比特位;无论本机的 long 类型的大小如何。version 指明文件格式的版本。

此函数可能失败,在这种情况下它会设置错误指示器。请使用 PyErr_Occurred() 进行检测。

void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)

将一个 Python 对象 value 以 marshal 格式写入 fileversion 指明文件格式的版本。

此函数可能失败,在这种情况下它会设置错误指示器。请使用 PyErr_Occurred() 进行检测。

PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
返回值:新的引用。

返回一个包含 value 的 marshal 表示形式的字节串对象。 version 指明文件格式的版本。

On error, raises an exception and returns NULL.

以下函数允许读取并恢复存储为 marshal 格式的值。

long PyMarshal_ReadLongFromFile(FILE *file)

从打开用于读取的 FILE* 对应的数据流返回一个 C long。使用此函数只能读取 32 位的值,无论本机 long 类型的大小如何。

On error, raises an exception and returns -1.

int PyMarshal_ReadShortFromFile(FILE *file)

从打开用于读取的 FILE* 对应的数据流返回一个 C short。使用此函数只能读取 16 位的值,无论本机 short 类型的大小如何。

On error, raises an exception and returns -1.

PyObject *PyMarshal_ReadObjectFromFile(FILE *file)
返回值:新的引用。

从打开用于读取的 FILE* 对应的数据流返回一个 Python 对象。

On error, raises an exception and returns NULL.

PyObject *PyMarshal_ReadLastObjectFromFile(FILE *file)
返回值:新的引用。

根据被打开用于读取的 FILE* 中的数据流返回一个 Python 对象。不同于 PyMarshal_ReadObjectFromFile(),此函数假定不会再从该文件读取更多的对象,允许其将文件数据积极地载入内存以便反序列化过程可以在内存中的数据上操作而不是每次从文件读取一个字节。 只有当你确定不会再从该文件读取任何内容时方可使用此变体形式。

On error, raises an exception and returns NULL.

PyObject *PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len)
返回值:新的引用。

data 所指向的包含 len 个字节的字节缓冲区对应的数据流返回一个 Python 对象。

On error, raises an exception and returns NULL.