Skip to content

Commit

Permalink
Fix loading of Python bindings on Windows when installed in arbitrary…
Browse files Browse the repository at this point in the history
… directory
  • Loading branch information
traversaro authored Oct 24, 2024
1 parent 481cc2a commit f0c286b
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions bindings/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,27 @@ if(FRAMEWORK_COMPILE_PYTHON_BINDINGS)
add_subdirectory(python)

# Create the __init__.py file
file(GENERATE
OUTPUT "${BLF_PYTHON_PACKAGE}/__init__.py"
CONTENT "from .bindings import *${NEW_LINE}from . import utils${NEW_LINE}")
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/__init__.py "")

# If we are on Windows and BUILD_SHARED_LIBS is ON, handle the fact that
# the Python interpreter does not look into PATH to find dll (see https://docs.python.org/3.8/library/os.html#os.add_dll_directory)
if(WIN32 AND BUILD_SHARED_LIBS)
if(IS_ABSOLUTE PYTHON_INSTDIR)
set(PYTHON_FULL_INSTDIR "${PYTHON_INSTDIR}")
else()
set(PYTHON_FULL_INSTDIR "${CMAKE_INSTALL_PREFIX}/${PYTHON_INSTDIR}")
endif()
file(RELATIVE_PATH RELATIVE_PATH_BETWEEN_INIT_PY_AND_DLL_DIRECTORY ${PYTHON_FULL_INSTDIR} ${CMAKE_INSTALL_FULL_BINDIR})
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" "import os${NEW_LINE}")
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" "library_dll_path = os.path.join(os.path.dirname(__file__),'${RELATIVE_PATH_BETWEEN_INIT_PY_AND_DLL_DIRECTORY}')${NEW_LINE}")
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" "# Avoid to call add_dll_directory if not necessary,${NEW_LINE}")
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" "# for example if the library to find are already found in the proper location in a conda environment${NEW_LINE}")
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" "if(library_dll_path != os.path.join(os.environ.get('CONDA_PREFIX', ''),'Library','bin') and library_dll_path != os.path.join(os.environ.get('CONDA_PREFIX', ''),'bin')):${NEW_LINE}")
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" " if(os.path.exists(library_dll_path)):${NEW_LINE}")
file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" " os.add_dll_directory(library_dll_path)${NEW_LINE}")
endif()

file(APPEND "${BLF_PYTHON_PACKAGE}/__init__.py" "from .bindings import *${NEW_LINE}from . import utils${NEW_LINE}")

# Install the __init__.py file
install(FILES "${BLF_PYTHON_PACKAGE}/__init__.py"
Expand Down

0 comments on commit f0c286b

Please sign in to comment.