数据 marshal 操作支持¶
这些例程允许 C 代码处理与 marshal
模块所用相同数据格式的序列化对象。 其中有些函数可用来将数据写入这种序列化格式,另一些函数则可用来读取并恢复数据。 用于存储 marshal 数据的文件必须以二进制模式打开。
数字值在存储时会将最低位字节放在开头。
此模块支持两种数据格式版本:第 0 版为历史版本,第 1 版本会在文件和 marshal 反序列化中共享固化的字符串。 第 2 版本会对浮点数使用二进制格式。 Py_MARSHAL_VERSION
指明了当前文件的格式(当前取值为 2)。
-
void
PyMarshal_WriteLongToFile
(long value, FILE *file, int version)¶ Marshal a
long
integer, value, to file. This will only write the least-significant 32 bits of value; regardless of the size of the nativelong
type. version indicates the file format.This function can fail, in which case it sets the error indicator. Use
PyErr_Occurred()
to check for that.
-
void
PyMarshal_WriteObjectToFile
(PyObject *value, FILE *file, int version)¶ 将一个 Python 对象 value 以 marshal 格式写入 file。 version 指明文件格式的版本。
This function can fail, in which case it sets the error indicator. Use
PyErr_Occurred()
to check for that.
-
PyObject *
PyMarshal_WriteObjectToString
(PyObject *value, int version)¶ - Return value: New reference.
返回一个包含 value 的 marshal 表示形式的字节串对象。 version 指明文件格式的版本。
以下函数允许读取并恢复存储为 marshal 格式的值。
-
long
PyMarshal_ReadLongFromFile
(FILE *file)¶ Return a C
long
from the data stream in aFILE*
opened for reading. Only a 32-bit value can be read in using this function, regardless of the native size oflong
.发生错误时,将设置适当的异常 (
EOFError
) 并返回-1
。
-
int
PyMarshal_ReadShortFromFile
(FILE *file)¶ Return a C
short
from the data stream in aFILE*
opened for reading. Only a 16-bit value can be read in using this function, regardless of the native size ofshort
.发生错误时,将设置适当的异常 (
EOFError
) 并返回-1
。
-
PyObject *
PyMarshal_ReadObjectFromFile
(FILE *file)¶ - Return value: New reference.
Return a Python object from the data stream in a
FILE*
opened for reading.发生错误时,将设置适当的异常 (
EOFError
,ValueError
或TypeError
) 并返回NULL
。
-
PyObject *
PyMarshal_ReadLastObjectFromFile
(FILE *file)¶ - Return value: New reference.
Return a Python object from the data stream in a
FILE*
opened for reading. UnlikePyMarshal_ReadObjectFromFile()
, this function assumes that no further objects will be read from the file, allowing it to aggressively load file data into memory so that the de-serialization can operate from data in memory rather than reading a byte at a time from the file. Only use these variant if you are certain that you won't be reading anything else from the file.发生错误时,将设置适当的异常 (
EOFError
,ValueError
或TypeError
) 并返回NULL
。
-
PyObject *
PyMarshal_ReadObjectFromString
(const char *data, Py_ssize_t len)¶ - Return value: New reference.
从包含指向 data 的 len 个字节的字节缓冲区对应的数据流返回一个 Python 对象。
发生错误时,将设置适当的异常 (
EOFError
,ValueError
或TypeError
) 并返回NULL
。