資料 marshal 操作的支援¶
這些例程允許 C 程式碼使用與 marshal 模組相同的資料格式來處理序列化物件。有函式可以將資料寫入序列化格式,還有其他函式可以用來讀取回資料。用來儲存 marshal 過的資料的檔案必須以二進位模式開啟。
數值會以最低有效位元組 (the least significant byte) 優先的方式儲存。
The module supports several versions of the data format; see
the Python module documentation for details.
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¶
The current format version. See
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 為 file。version 表示檔案的格式。
這個函式可能會失敗,這時會設定錯誤指示器。使用
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。無論 long 的原生大小如何,這個函式只能讀取 32 位元的值。
On error, raises an exception and returns
-1.
-
int PyMarshal_ReadShortFromFile(FILE *file)¶
從一個為讀取而開啟的 FILE* 中的資料串流回傳一個 C short。無論 short 的原生大小如何,這個函式只能讀取 16 位元的值。
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)¶
- 回傳值:新的參照。
從一個包含 len 位元組、被 data 指向的位元組緩衝區中的資料串流回傳一個 Python 物件。
On error, raises an exception and returns
NULL.