Skip to content

Commit

Permalink
Merge pull request #1209 from robotology/fixwinpy
Browse files Browse the repository at this point in the history
Fix loading of Python bindings on Windows when installed in arbitrary directory
  • Loading branch information
traversaro authored Sep 29, 2024
2 parents 4798cb1 + 465fc82 commit 5fe4cf9
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions bindings/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,26 @@ if (IDYNTREE_USES_PYTHON_PYBIND11 OR IDYNTREE_USES_PYTHON)
# Install main __init__.py
# Clear the file first if it exists.
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 ${CMAKE_CURRENT_BINARY_DIR}/__init__.py "import os${NEW_LINE}")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/__init__.py "library_dll_path = os.path.join(os.path.dirname(__file__),'${RELATIVE_PATH_BETWEEN_INIT_PY_AND_DLL_DIRECTORY}')${NEW_LINE}")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/__init__.py "# Avoid to call add_dll_directory if not necessary,${NEW_LINE}")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/__init__.py "# for example if the library to find are already found in the proper location in a conda${NEW_LINE}")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/__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 ${CMAKE_CURRENT_BINARY_DIR}/__init__.py " if(os.path.exists(library_dll_path)):${NEW_LINE}")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/__init__.py " os.add_dll_directory(library_dll_path)${NEW_LINE}")
endif()


# If pybind is enabled, add the corresponding import.
if (${IDYNTREE_USES_PYTHON_PYBIND11})
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/__init__.py "from . import pybind${NEW_LINE}")
Expand Down

0 comments on commit 5fe4cf9

Please sign in to comment.