CLR Loader
clr-loader is a pure Python library designed for loading .NET runtimes (CoreCLR, Mono, Full .NET Framework), loading .NET assemblies, and interacting with them. It primarily serves as a low-level backend for the pythonnet library but can be used standalone for specific scenarios. Version 0.3.0 is the current release, requiring Python 3.10 or newer. Releases are made on an as-needed basis, often in sync with pythonnet development.
Warnings
- breaking clr-loader version 0.3.0 and newer explicitly require Python 3.10 or higher. Older Python versions are no longer supported.
- gotcha clr-loader is a loader, not a runtime provider. It requires a .NET runtime (e.g., .NET Core SDK, .NET Runtime, or Mono) to be installed and discoverable on the system. The library itself does not bundle or install a .NET runtime.
- gotcha While clr-loader can be used standalone, its primary purpose is to be a low-level backend for pythonnet. Direct interaction with loaded assemblies and .NET objects in a user-friendly Pythonic way is best achieved through pythonnet, which leverages clr-loader internally.
- gotcha The public API for loading runtimes are `clr_loader.get_coreclr()` and `clr_loader.get_mono()`. Directly importing from submodules like `clr_loader.hostfxr` or `clr_loader.mono` is not part of the stable public API and can lead to breaking changes in minor versions.
Install
-
pip install clr-loader
Imports
- get_coreclr
from clr_loader import get_coreclr
- get_mono
from clr_loader import get_mono
- ClrError
from clr_loader.exceptions import ClrError
Quickstart
import os
from clr_loader import get_coreclr
from clr_loader.exceptions import ClrError
# clr-loader attempts to find the latest installed CoreCLR runtime.
# This might require a .NET SDK or runtime to be installed on the system.
# For CI/CD or specific versions, you might need to provide `runtime_config`.
try:
print("Attempting to load CoreCLR runtime...")
# This call tries to auto-discover an installed .NET runtime.
# If no .NET runtime is installed or discoverable, this will raise ClrError.
clr_runtime_host = get_coreclr()
print(f"Successfully loaded CoreCLR host: {clr_runtime_host}")
# For advanced usage, one would then use clr_runtime_host
# to load assemblies and interact with them, typically via pythonnet.
# Example (conceptual, requires a .NET assembly and more setup):
# assembly_path = os.path.join(os.getcwd(), "MyDotNetLib.dll")
# loaded_assembly = clr_runtime_host.load_assembly_from(assembly_path.encode('utf-8'))
# print(f"Loaded assembly: {loaded_assembly.name}")
except ClrError as e:
print(f"Error loading CoreCLR: {e}")
print("This typically means a .NET runtime (e.g., .NET SDK or runtime) is not installed")
print("or not discoverable on your system. Please install .NET and ensure it's in PATH,")
print("or provide a specific runtime_config.json path to get_coreclr().")
except Exception as e:
print(f"An unexpected error occurred: {e}")