When using the raw API, you must manually ensure that Python objects (like buffers or callback functions) remain in memory as long as the underlying C resources (like an FPDF_DOCUMENT) depend on them. If Python garbage collects an object while PDFium is still using it, it will lead to memory corruption or segmentation faults.
Pattern for custom file access:
If using FPDF_LoadCustomDocument, the FPDF_FILEACCESS structure and its associated callback functions must be kept alive until FPDF_CloseDocument is called. A common pattern is to wrap these in a 'Data Holder' class that maintains references to the buffer and the callback function.
class PdfDataHolder:
def __init__(self, buffer, function):
self.buffer = buffer
self.function = function # Keeps the callback alive
def close(self):
id(self.function) # Ensure function is alive until this point
self.buffer.close()
# Usage
data_holder = PdfDataHolder(py_buffer, fileaccess.m_GetBlock)
pdf = pdfium_c.FPDF_LoadCustomDocument(fileaccess, None)
# ... work with pdf ...
pdfium_c.FPDF_CloseDocument(pdf)
data_holder.close()