diff --git a/src/pypdfium2/__init__.py b/src/pypdfium2/__init__.py index e93b58376..3345781ef 100644 --- a/src/pypdfium2/__init__.py +++ b/src/pypdfium2/__init__.py @@ -1,16 +1,7 @@ # SPDX-FileCopyrightText: 2023 geisserml # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause -import atexit -import logging +import pypdfium2._library_scope from pypdfium2.version import * from pypdfium2._helpers import * from pypdfium2 import raw, internal - -logger = logging.getLogger(__name__) # FIXME perhaps unnecessary? - -# Note: PDFium developers plan changes to the initialisation API (see https://crbug.com/pdfium/1446) -raw.FPDF_InitLibrary() -atexit.register(raw.FPDF_DestroyLibrary) - -del atexit, logging diff --git a/src/pypdfium2/__main__.py b/src/pypdfium2/__main__.py index fcf8bfd41..4b30f23f9 100644 --- a/src/pypdfium2/__main__.py +++ b/src/pypdfium2/__main__.py @@ -58,8 +58,7 @@ def get_parser(): def setup_logging(): - debug_autoclose = bool(int( os.environ.get("DEBUG_AUTOCLOSE", 0) )) - pdfium_i.set_autoclose_debug(debug_autoclose) + pdfium_i.DEBUG_AUTOCLOSE.value = bool(int( os.environ.get("DEBUG_AUTOCLOSE", 0) )) lib_logger = logging.getLogger("pypdfium2") lib_logger.addHandler(logging.StreamHandler()) diff --git a/src/pypdfium2/_library_scope.py b/src/pypdfium2/_library_scope.py new file mode 100644 index 000000000..b600a7667 --- /dev/null +++ b/src/pypdfium2/_library_scope.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2023 geisserml +# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause + +import atexit +import pypdfium2.raw as pdfium_c +import pypdfium2.internal as pdfium_i + + +def destroy_library(): + if pdfium_i.DEBUG_AUTOCLOSE: + import os, sys + os.write(sys.stderr.fileno(), b"Destroy PDFium (auto)\n") + pdfium_c.FPDF_DestroyLibrary() + +# Load pdfium +# Note: PDFium developers plan changes to the initialisation API (see https://crbug.com/pdfium/1446) +pdfium_c.FPDF_InitLibrary() + +# Register an exit handler that will free pdfium +# Trust in Python to call exit handlers only after all objects have been finalized +atexit.register(destroy_library) diff --git a/src/pypdfium2/internal/bases.py b/src/pypdfium2/internal/bases.py index 1c9e5406a..94a2f66f7 100644 --- a/src/pypdfium2/internal/bases.py +++ b/src/pypdfium2/internal/bases.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2023 geisserml # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause -__all__ = ("AutoCastable", "AutoCloseable", "set_autoclose_debug") +__all__ = ("AutoCastable", "AutoCloseable", "DEBUG_AUTOCLOSE") import os import sys @@ -12,7 +12,8 @@ logger = logging.getLogger(__name__) -DEBUG_AUTOCLOSE = False + +DEBUG_AUTOCLOSE = ctypes.c_bool(False) # mutable bool STATE_INVALID = -1 STATE_AUTO = 0 @@ -20,11 +21,6 @@ STATE_BYPARENT = 2 -def set_autoclose_debug(value=True): - global DEBUG_AUTOCLOSE - DEBUG_AUTOCLOSE = value - - class AutoCastable: @property