### RuntimeInfo String Representation Source: https://pythonnet.github.io/clr-loader/reference.html Demonstrates how to get a readable string representation of RuntimeInfo, which includes version, initialization, and shutdown status. ```python >>> ri = RuntimeInfo() >>> print(ri) 6.12.0.122 (tarball) Runtime: Mono ============= Version: 6.12.0.122 (tarball) Initialized: True Shut down: False Properties: ``` -------------------------------- ### Find Installed .NET Core Runtimes Source: https://pythonnet.github.io/clr-loader/reference.html Discovers installed .NET Core runtimes by parsing the output of 'dotnet --list-runtimes' or by enumerating runtimes in the 'shared' subdirectory of the .NET Core root. ```python clr_loader.find_runtimes() → Iterator[DotnetCoreRuntimeSpec] ``` -------------------------------- ### C# Method Signature Example Source: https://pythonnet.github.io/pythonnet/codecs.html Illustrates a C# method that can be called from Python, showing automatic type conversion for primitive types. ```csharp void Foo(int bar) { ... } ``` -------------------------------- ### DotnetCoreRuntimeSpec Class Source: https://pythonnet.github.io/clr-loader/reference.html Represents the specification of an installed .NET Core runtime. ```APIDOC ## class clr_loader.DotnetCoreRuntimeSpec ### Description Specification of an installed .NET Core runtime. ``` -------------------------------- ### Runtime Management Functions Source: https://pythonnet.github.io/pythonnet/genindex.html Functions for interacting with the .NET runtime, including getting information, setting it from environment variables, and setting it directly. ```APIDOC ## get_runtime_info() ### Description Retrieves information about the current .NET runtime. ### Method GET ### Endpoint /api/runtime/info ### Parameters None ### Response #### Success Response (200) - **runtime_info** (object) - Details about the .NET runtime. #### Response Example ```json { "runtime_info": { "version": "6.0.0", "framework": ".NETCoreApp,Version=v6.0" } } ``` ``` ```APIDOC ## set_runtime() ### Description Sets the .NET runtime explicitly. ### Method POST ### Endpoint /api/runtime/set ### Parameters #### Request Body - **runtime_path** (string) - Required - The path to the .NET runtime. ### Request Example ```json { "runtime_path": "/path/to/dotnet/runtime" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Runtime set successfully." } ``` ``` ```APIDOC ## set_runtime_from_env() ### Description Sets the .NET runtime by detecting it from environment variables. ### Method POST ### Endpoint /api/runtime/set/env ### Parameters None ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Runtime set from environment variables." } ``` ``` -------------------------------- ### Get Assembly Wrapper Source: https://pythonnet.github.io/clr-loader/reference.html Retrieves a wrapper for a .NET assembly. Note that this function does not guarantee the assembly is loaded; loading occurs upon first reference. ```python get_assembly(_assembly_path : str | PathLike[str]_) → Assembly ``` -------------------------------- ### Find .NET Core Root Directory Source: https://pythonnet.github.io/clr-loader/reference.html Attempts to locate the .NET Core root directory by checking environment variables, default installation paths, or the 'dotnet' CLI tool. ```python clr_loader.find_dotnet_root() → Path ``` -------------------------------- ### Access Fields and Properties Source: https://pythonnet.github.io/pythonnet/python.html Get and set fields and properties of CLR objects using standard attribute access. ```python from System import Environment name = Environment.MachineName Environment.ExitCode = 1 ``` -------------------------------- ### Define C# Test Class Source: https://pythonnet.github.io/clr-loader/_sources/usage.rst.txt Example C# class structure designed to be called from Python via clr_loader. ```csharp using System.Text; using System.Runtime.InteropServices; using System; namespace Example { public class TestClass { public static int Test(IntPtr arg, int size) { var buf = new byte[size]; Marshal.Copy(arg, buf, 0, size); var bufAsString = Encoding.UTF8.GetString(buf); var result = bufAsString.Length; Console.WriteLine($"Called {nameof(Test)} in {nameof(TestClass)} with {bufAsString}, returning {result}"); Console.WriteLine($"Binary data: {Convert.ToBase64String(buf)}"); return result; } } } ``` -------------------------------- ### Attribute Management Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for getting, setting, checking, and deleting attributes on a Python object. ```APIDOC ## HasAttr ### Description Returns true if the object has an attribute with the given name. ## GetAttr ### Description Returns the named attribute of the Python object. Optionally accepts a default value to return if an AttributeError occurs. ## SetAttr ### Description Sets an attribute of the object with the given name and value. ## DelAttr ### Description Deletes the named attribute of the Python object. ``` -------------------------------- ### Get Wrapped .NET Function Source: https://pythonnet.github.io/clr-loader/reference.html Obtains a wrapped .NET static function instance. The function must have the signature `int Func(IntPtr ptr, int size)` and will be called with a pointer to a binary buffer. ```python get_function(_name : str_, _func : str | None = None_) → ClrFunction ``` -------------------------------- ### Demonstrating Value Type Boxing Issue Source: https://pythonnet.github.io/pythonnet/python.html This example shows how attempting to modify a value type property directly in an array fails because the access creates a boxed copy. ```python items = System.Array.CreateInstance(Point, 3) for i in range(3): items[i] = Point(0, 0) items[0].X = 1 # won't work!! ``` -------------------------------- ### Implement and use delegates Source: https://pythonnet.github.io/pythonnet/python.html Shows how to instantiate managed delegates with Python callables and manage multicast delegates. ```python def my_handler(source, args): print('my_handler called!') # instantiate a delegate d = AssemblyLoadEventHandler(my_handler) # use it as an event handler AppDomain.CurrentDomain.AssemblyLoad += d ``` ```python d += self.method1 d += self.method2 d() ``` -------------------------------- ### Build Python.NET from source Source: https://pythonnet.github.io/pythonnet/python.html Command to build the package from a source distribution or repository clone. ```bash python setup.py build ``` -------------------------------- ### clr_loader.get_netfx Source: https://pythonnet.github.io/clr-loader/reference.html Initializes and returns a .NET Framework runtime instance. ```APIDOC ## clr_loader.get_netfx ### Description Get a .NET Framework runtime instance. ### Parameters - **domain** (str) - Optional - Name of the domain to create - **config_file** (str | PathLike[str]) - Optional - Configuration file to use for non-root-domains ### Response - **Runtime** (Object) - A .NET Framework runtime instance ``` -------------------------------- ### Register and fire events Source: https://pythonnet.github.io/pythonnet/python.html Demonstrates the C#-like syntax for event registration and invocation in Python. ```python def handler(source, args): print('my_handler called!') # register event handler object.SomeEvent += handler # unregister event handler object.SomeEvent -= handler # fire the event result = object.SomeEvent(...) ``` -------------------------------- ### Configure runtime via environment variables Source: https://pythonnet.github.io/pythonnet/python.html Sets the runtime and configuration parameters using shell environment variables. ```bash PYTHONNET_RUNTIME=coreclr PYTHONNET_CORECLR_RUNTIME_CONFIG=/path/to/runtimeconfig.json ``` -------------------------------- ### Handle out and ref parameters Source: https://pythonnet.github.io/pythonnet/python.html Demonstrates how managed methods with out or ref parameters return values to Python. ```python new_arg = someobject.SomeMethod1(arg) ``` ```python new_arg, new_arg2 = someobject.SomeMethod2(arg, arg2) ``` ```python found, new_value = dictionary.TryGetValue(key, value) ``` -------------------------------- ### clr_loader.get_mono Source: https://pythonnet.github.io/clr-loader/reference.html Initializes and returns a Mono runtime instance. ```APIDOC ## clr_loader.get_mono ### Description Get a Mono runtime instance. ### Parameters - **config_file** (str | PathLike[str]) - Optional - Path to the domain configuration file - **global_config_file** (str | PathLike[str]) - Optional - Path to the global configuration file - **libmono** (str | PathLike[str]) - Optional - Path to the Mono runtime dll/so/dylib - **sgen** (bool) - Optional - Passed to find_libmono if libmono is not specified - **debug** (bool) - Optional - Whether to initialise Mono debugging - **jit_options** (Sequence[str]) - Optional - Command line options passed to mono_jit_parse_options - **assembly_dir** (str | PathLike[str]) - Optional - Base directory for assemblies - **config_dir** (str | PathLike[str]) - Optional - Base directory for configuration files - **set_signal_chaining** (bool) - Optional - Whether to enable signal chaining - **trace_mask** (str) - Optional - Trace mask - **trace_level** (str) - Optional - Trace level ### Response - **Runtime** (Object) - A Mono runtime instance ``` -------------------------------- ### Instantiate Managed Classes Source: https://pythonnet.github.io/pythonnet/python.html Create instances of managed classes using standard Python instantiation syntax. ```python from System.Drawing import Point p = Point(5, 5) ``` -------------------------------- ### Correcting Value Type Updates Source: https://pythonnet.github.io/pythonnet/python.html This example demonstrates the workaround for modifying value types in an array by explicitly re-setting the array member after modification. ```python items = System.Array.CreateInstance(Point, 3) for i in range(3): items[i] = Point(0, 0) # This _will_ work. We get 'item' as a boxed copy of the Point # object actually stored in the array. After making our changes # we re-set the array item to update the bits in the array. item = items[0] item.X = 1 items[0] = item ``` -------------------------------- ### Initialize CoreCLR Runtime Source: https://pythonnet.github.io/clr-loader/_sources/usage.rst.txt Initializes a CoreCLR runtime instance using default configuration. ```python from clr_loader import get_coreclr runtime = get_coreclr() ``` -------------------------------- ### Utilities Source: https://pythonnet.github.io/clr-loader/_sources/reference.rst.txt Utility classes and functions for runtime discovery and configuration. ```APIDOC ## Utilities ### Description Helper classes and functions for discovering .NET installations and runtime specifications. ### Classes - **RuntimeInfo**: Provides information about the current runtime. - **DotnetCoreRuntimeSpec**: Specification for .NET Core runtime configurations. ### Functions - **find_dotnet_root()**: Locates the .NET root directory. - **find_libmono()**: Locates the libmono library. - **find_runtimes()**: Discovers available .NET runtimes. ``` -------------------------------- ### Construct a Runtime instance manually Source: https://pythonnet.github.io/pythonnet/python.html Provides fine-grained control by creating a runtime instance via clr_loader and setting it explicitly. ```python from pythonnet import set_runtime from clr_loader import get_coreclr rt = get_coreclr(runtime_config="/path/to/runtimeconfig.json") set_runtime(rt) ``` -------------------------------- ### Runtime Management Functions Source: https://pythonnet.github.io/clr-loader/genindex.html Functions for discovering and initializing .NET runtimes. ```APIDOC ## find_dotnet_root() ### Description Locates the root directory of the .NET installation. ## find_libmono() ### Description Locates the Mono library on the system. ## find_runtimes() ### Description Discovers available .NET runtimes on the system. ## get_coreclr() ### Description Initializes and returns a CoreCLR runtime instance. ## get_mono() ### Description Initializes and returns a Mono runtime instance. ## get_netfx() ### Description Initializes and returns a .NET Framework runtime instance. ``` -------------------------------- ### PyTuple and PyList Operations Source: https://pythonnet.github.io/pythonnet/reference.html Constructors and utility methods for Python tuple and list objects. ```APIDOC ## PyTuple and PyList ### Description Classes representing Python tuple and list objects with constructors for wrapping existing objects or creating new ones. ### PyTuple Methods - **IsTupleType(PyObject value)**: Returns true if the object is a tuple. - **AsTuple(PyObject value)**: Converts a Python object to a tuple. ### PyList Methods - **PyList(PyObject o)**: Copy constructor for PyList. ``` -------------------------------- ### Runtime Info Source: https://pythonnet.github.io/clr-loader/reference.html Provides configuration and version information about the CLR runtime. ```python abstractmethod info() → RuntimeInfo ``` -------------------------------- ### Wrapper Types Source: https://pythonnet.github.io/clr-loader/_sources/reference.rst.txt Core classes for interacting with loaded .NET runtimes and assemblies. ```APIDOC ## Wrapper Types ### Description Classes representing the runtime environment and loaded assemblies. ### Classes - **Runtime**: Represents a loaded .NET runtime. - **Assembly**: Represents a loaded .NET assembly. ``` -------------------------------- ### Registering and Managing Codec Priorities Source: https://pythonnet.github.io/pythonnet/_sources/codecs.rst.txt Use EncoderGroup and DecoderGroup to manage codec priorities. New codecs can be added to groups, and groups can be registered with PyObjectConversions. ```csharp public static EncoderGroup HighPriorityEncoders{ get; } = new EncoderGroup(); void Init() { PyObjectConversions.RegisterEncoder(HighPriorityEncoders); var lowPriorityEncoder = new SomeEncoder(); PyObjectConversions.RegisterEncoder(lowPriorityEncoder); } ... some time later HighPriorityEncoders.Add(new SomeOtherEncoder()); ``` -------------------------------- ### clr_loader.get_coreclr Source: https://pythonnet.github.io/clr-loader/reference.html Initializes and returns a CoreCLR (.NET Core) runtime instance. ```APIDOC ## clr_loader.get_coreclr ### Description Get a CoreCLR (.NET Core) runtime instance. The returned DotnetCoreRuntime acts as a mapping of config properties. ### Parameters - **runtime_config** (str | PathLike[str]) - Optional - Path to a runtimeconfig.json - **entry_dll** (str | PathLike[str]) - Optional - Path to the entry dll - **dotnet_root** (str | PathLike[str]) - Optional - Root directory of the .NET Core installation - **properties** (dict[str, str]) - Optional - Additional runtime properties - **runtime_spec** (DotnetCoreRuntimeSpec) - Optional - Concrete runtime to use - **runtime_version** (str) - Optional - Major.minor version of the runtime ### Response - **Runtime** (Object) - A CoreCLR runtime instance ``` -------------------------------- ### pythonnet.load() Source: https://pythonnet.github.io/pythonnet/pyreference.html Loads the Python.NET runtime with specified parameters. ```APIDOC ## POST pythonnet.load() ### Description Load Python.NET in the specified runtime. If no environment is set, it defaults to set_default_runtime. ### Parameters #### Request Body - **runtime** (Runtime | str | None) - Optional - The runtime to load. - **params** (str) - Optional - Additional configuration parameters. ``` -------------------------------- ### Dir Method Source: https://pythonnet.github.io/pythonnet/reference.html Returns a list of attribute names for an object. ```APIDOC ## Dir () ### Description Return a list of the names of the attributes of the object. This is equivalent to the Python expression “dir(object)”. ### Method PyList ``` -------------------------------- ### PythonEngine Runtime Management Source: https://pythonnet.github.io/pythonnet/reference.html Methods for initializing, shutting down, and managing the Python runtime environment. ```APIDOC ## PythonEngine Methods ### Initialize - **Description**: Initialize the Python runtime. - **Parameters**: - **_args_** (IEnumerable) - Required - Arguments for initialization. - **_setSysArgv_** (bool) - Optional - Whether to set sys.argv (default: true). - **_initSigs_** (bool) - Optional - Whether to initialize signals (default: false). ### Shutdown - **Description**: Shutdown and release resources held by the Python runtime. ### Eval - **Description**: Evaluate a Python expression and return the result. - **Parameters**: - **_code_** (string) - Required - Python expression string. - **_globals_** (PyDict) - Optional - Global dictionary. - **_locals_** (PyObject) - Optional - Local dictionary. ### Exec - **Description**: Run a string containing Python code. - **Parameters**: - **_code_** (string) - Required - Python code string. - **_globals_** (PyDict) - Optional - Global dictionary. - **_locals_** (PyObject) - Optional - Local dictionary. ``` -------------------------------- ### Load Assembly Source: https://pythonnet.github.io/clr-loader/_sources/usage.rst.txt Loads a compiled .NET assembly into the runtime. ```python assembly = runtime.get_assembly("path/to/assembly.dll") ``` -------------------------------- ### pythonnet.get_runtime_info() Source: https://pythonnet.github.io/pythonnet/pyreference.html Retrieves information about the currently configured runtime. ```APIDOC ## GET pythonnet.get_runtime_info() ### Description Retrieve information on the configured runtime. ### Response #### Success Response (200) - **RuntimeInfo** (object) - Information about the configured runtime or None if not configured. ``` -------------------------------- ### RuntimeInfo Class Source: https://pythonnet.github.io/clr-loader/reference.html Provides information about a CLR Runtime instance. ```APIDOC ## class clr_loader.RuntimeInfo ### Description Information on a Runtime instance. An informative text can be retrieved from this by converting it to a `str`, in particular the following results in readable debug information: ```python >>> ri = RuntimeInfo() >>> print(ri) 6.12.0.122 (tarball) Runtime: Mono ============= Version: 6.12.0.122 (tarball) Initialized: True Shut down: False Properties: ``` ``` -------------------------------- ### Utility Functions Source: https://pythonnet.github.io/clr-loader/reference.html Utility functions for discovering .NET Core runtimes and libraries. ```APIDOC ## Utilities ### find_dotnet_root ```python find_dotnet_root() -> Path ``` ##### Description Try to discover the .NET Core root directory. If the environment variable `DOTNET_ROOT` is defined, we will use that. Otherwise, we probe the default installation paths on Windows and macOS. If none of these lead to a result, we try to discover the `dotnet` CLI tool and use its (real) parent directory. Otherwise, this function raises an exception. ##### Returns Path to the .NET Core root. ### find_libmono ```python find_libmono(_*_ , _assembly_dir : str | PathLike[str] | None = None_, _sgen : bool = True_) -> Path ``` ##### Description Find a suitable libmono dynamic library. On Windows and macOS, we check the default installation directories. ##### Parameters - **sgen** (bool) - Whether to look for an SGen or Boehm GC instance. This parameter is ignored on Windows, as only `sgen` is installed with the default installer. ##### Returns Path to usable `libmono`. ### find_runtimes ```python find_runtimes() -> Iterator[DotnetCoreRuntimeSpec] ``` ##### Description Find installed .NET Core runtimes. If the `dotnet` CLI can be found, we will call it as `dotnet --list-runtimes` and parse the result. If it is not available, we try to discover the dotnet root directory using `find_dotnet_root()` and enumerate the runtimes installed in the `shared` subdirectory. ##### Returns Iterable of `DotnetCoreRuntimeSpec` objects. ``` -------------------------------- ### pythonnet Module Reference Source: https://pythonnet.github.io/pythonnet/_sources/pyreference.rst.txt API documentation for the pythonnet module, covering runtime loading and configuration functions. ```APIDOC ## pythonnet Module ### Description The pythonnet module provides the core functionality for loading the Python runtime and configuring the bridge between Python and .NET. ### Members - **load_runtime()** - Initializes the Python runtime within the .NET process. - **set_runtime_path(path)** - Configures the path to the Python runtime installation. - **get_runtime_info()** - Retrieves information about the currently loaded Python runtime. ``` -------------------------------- ### PyInt Class Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for creating and converting Python integer objects. ```APIDOC ## PyInt Class ### Description Represents a Python integer object with various constructors and conversion methods. ### Methods - **Constructors** - Supports initialization from PyObject, int, uint, long, ulong, short, ushort, byte, sbyte, and string. - **ToInt16()** - Returns the value as an int16. - **ToInt32()** - Returns the value as an int32. - **ToInt64()** - Returns the value as an int64. - **IsIntType(PyObject value)** - Returns true if the object is a Python int. - **AsInt(PyObject value)** - Converts a Python object to a Python int. ``` -------------------------------- ### Bind Generic Methods Source: https://pythonnet.github.io/pythonnet/python.html Bind generic methods at runtime using subscript syntax directly on the method. ```python someobject.SomeGenericMethod[UInt32](10) someobject.SomeGenericMethod[String]("10") ``` -------------------------------- ### Factory Functions Source: https://pythonnet.github.io/clr-loader/_sources/reference.rst.txt Functions used to initialize and retrieve specific .NET runtime instances. ```APIDOC ## Factory Functions ### Description Functions to initialize and retrieve specific .NET runtime instances. ### Functions - **get_mono()**: Retrieves a Mono runtime instance. - **get_coreclr()**: Retrieves a CoreCLR runtime instance. - **get_netfx()**: Retrieves a NetFX runtime instance. ``` -------------------------------- ### Invoke Methods and Inspect Signatures Source: https://pythonnet.github.io/pythonnet/python.html Call CLR methods directly and inspect signatures using __doc__ or the help function. ```python from System import Environment drives = Environment.GetLogicalDrives() ``` ```python from System import Environment print(Environment.GetFolderPath.__doc__) help(Environment) ``` -------------------------------- ### Load a .NET runtime explicitly Source: https://pythonnet.github.io/pythonnet/python.html Configures the runtime using the load function before importing the clr module. ```python from pythonnet import load load("coreclr", runtime_config="/path/to/runtimeconfig.json") ``` -------------------------------- ### Iterate over collections Source: https://pythonnet.github.io/pythonnet/python.html Demonstrates iterating over managed objects that implement IEnumerable. ```python domain = System.AppDomain.CurrentDomain for item in domain.GetAssemblies(): name = item.GetName() ``` -------------------------------- ### Assembly Class Source: https://pythonnet.github.io/clr-loader/reference.html Represents a .NET assembly and provides methods to interact with its functions. ```APIDOC ## class clr_loader.Assembly ### Description Represents a .NET assembly and provides methods to interact with its functions. ### Methods #### get_function ```python get_function(_name : str_, _func : str | None = None_) -> ClrFunction ``` ##### Description Get a wrapped .NET function instance. The function must be `static`, and it must have the signature `int Func(IntPtr ptr, int size)`. The returned wrapped instance will take a `binary` and call the .NET function with a pointer to that buffer and the buffer length. The buffer is reflected using CFFI’s from_buffer. ##### Parameters - **name** (str) - If `func` is not given, this is the fully qualified name of the function. If `func` is given, this is the fully qualified name of the containing class. - **func** (str | None) - Name of the function. ##### Returns A function object that takes a single `binary` parameter and returns an `int`. ``` -------------------------------- ### pythonnet.set_runtime_from_env() Source: https://pythonnet.github.io/pythonnet/pyreference.html Configures the runtime based on environment variables. ```APIDOC ## POST pythonnet.set_runtime_from_env() ### Description Set up the runtime using the environment variable PYTHONNET_RUNTIME and related configuration variables. ``` -------------------------------- ### Use Indexers Source: https://pythonnet.github.io/pythonnet/python.html Access managed indexers using standard Python indexing syntax or C#-style notation for overloads. ```python from System.Collections import Hashtable table = Hashtable() table["key 1"] = "value 1" ``` ```python items[0, 2] items[0, 2, 3] ``` -------------------------------- ### Create and manipulate arrays Source: https://pythonnet.github.io/pythonnet/python.html Covers creating managed arrays and using standard Python sequence protocols for access. ```python from System import Array, Int32 myarray = Array[Int32](10) ``` ```python items = SomeObject.GetArray() # Get first item v = items[0] items[0] = v # Get last item v = items[-1] items[-1] = v # Get length l = len(items) # Containment test test = v in items ``` ```python items[0, 2] items[0, 2, 3] ``` -------------------------------- ### Runtime Class Methods Source: https://pythonnet.github.io/clr-loader/genindex.html Methods available on the Runtime class for managing assemblies and runtime state. ```APIDOC ## Runtime.get_assembly() ### Description Loads an assembly into the current runtime. ## Runtime.info() ### Description Returns information about the current runtime instance. ## Runtime.shutdown() ### Description Shuts down the current runtime instance. ``` -------------------------------- ### Handle managed exceptions Source: https://pythonnet.github.io/pythonnet/python.html Shows how to raise and catch managed exceptions using standard Python try-except blocks. ```python from System import NullReferenceException try: raise NullReferenceException("aiieee!") except NullReferenceException as e: print(e.Message) print(e.Source) ``` -------------------------------- ### pythonnet.set_runtime() Source: https://pythonnet.github.io/pythonnet/pyreference.html Configures a clr_loader runtime without immediately loading it. ```APIDOC ## POST pythonnet.set_runtime() ### Description Set up a clr_loader runtime without loading it. ### Parameters #### Request Body - **runtime** (Runtime | str) - Required - Either an initialized clr_loader runtime, or one of netfx, coreclr, mono, or default. - **params** (str) - Optional - Additional configuration parameters. ``` -------------------------------- ### Repr Method Source: https://pythonnet.github.io/pythonnet/reference.html Returns the string representation of an object (equivalent to Python's repr()). ```APIDOC ## Repr () ### Description Return a string representation of the object. This method is the managed equivalent of the Python expression “repr(object)”. ### Method string? ``` -------------------------------- ### PyList Class Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for creating and manipulating Python list objects. ```APIDOC ## PyList Class ### Description Provides methods to create and manipulate Python list objects. ### Methods - **PyList()** - Creates a new empty Python list object. - **PyList(PyObject[] items)** - Creates a new Python list object from an array of objects. - **Append(PyObject item)** - Appends an item to the list. - **Insert(int index, PyObject item)** - Inserts an item at the given index. - **Reverse()** - Reverses the list in place. - **Sort()** - Sorts the list in place. - **IsListType(PyObject value)** - Returns true if the object is a Python list. - **AsList(PyObject value)** - Converts a Python object to a Python list. ``` -------------------------------- ### ToString Method Source: https://pythonnet.github.io/pythonnet/reference.html Returns the string representation of an object (equivalent to Python's str()). ```APIDOC ## ToString () ### Description Return the string representation of the object. This method is the managed equivalent of the Python expression “str(object)”. ### Method string ### Overrides object.ToString() ``` -------------------------------- ### Module Loading and Unloading Source: https://pythonnet.github.io/pythonnet/genindex.html Functions for loading and unloading Python modules within the .NET environment. ```APIDOC ## load() ### Description Loads a Python module. ### Method POST ### Endpoint /api/module/load ### Parameters #### Request Body - **module_name** (string) - Required - The name of the module to load. ### Request Example ```json { "module_name": "my_module" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the module was loaded successfully. #### Response Example ```json { "status": "loaded" } ``` ``` ```APIDOC ## unload() ### Description Unloads a Python module. ### Method POST ### Endpoint /api/module/unload ### Parameters #### Request Body - **module_name** (string) - Required - The name of the module to unload. ### Request Example ```json { "module_name": "my_module" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the module was unloaded successfully. #### Response Example ```json { "status": "unloaded" } ``` ``` -------------------------------- ### Load assemblies with AddReference Source: https://pythonnet.github.io/pythonnet/python.html Explicitly loads a .NET assembly before importing its types. ```python import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import Form ``` -------------------------------- ### Assembly Class Methods Source: https://pythonnet.github.io/clr-loader/genindex.html Methods available on the Assembly class for interacting with loaded .NET assemblies. ```APIDOC ## Assembly.get_function() ### Description Retrieves a function pointer or callable from the loaded assembly. ``` -------------------------------- ### Python.Runtime.PyBuffer API Source: https://pythonnet.github.io/pythonnet/reference.html Methods for handling Python buffer objects and memory access. ```APIDOC ## PyBuffer Methods ### Description Provides methods for interacting with Python buffer protocols, including memory access and disposal. ### Methods - IsContiguous() - GetPointer() - FromContiguous() - ToContiguous() - Write() - Read() - Dispose() - SizeFromFormat() ``` -------------------------------- ### PySequence Class Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for interacting with Python sequence objects in C#. ```APIDOC ## PySequence Methods ### Description Provides methods equivalent to the Python abstract sequence API for manipulating sequences like lists, strings, and tuples. ### Methods - **GetSlice(int i1, int i2)**: Returns the slice of the sequence. - **SetSlice(int i1, int i2, PyObject v)**: Sets the slice of the sequence. - **DelSlice(int i1, int i2)**: Deletes the slice of the sequence. - **Index(PyObject item)**: Returns the index of the item. - **Contains(PyObject item)**: Returns true if the sequence contains the item. - **Concat(PyObject other)**: Concatenates two sequences. - **Repeat(int count)**: Repeats the sequence N times. ### Static Methods - **IsSequenceType(PyObject value)**: Returns true if the object implements the sequence protocol. ``` -------------------------------- ### Find libmono Dynamic Library Source: https://pythonnet.github.io/clr-loader/reference.html Locates a suitable libmono dynamic library, optionally considering the System Generation (SGen) garbage collector. This function is primarily for non-Windows platforms. ```python clr_loader.find_libmono(_*_ , _assembly_dir : str | PathLike[str] | None = None_, _sgen : bool = True_) → Path ``` -------------------------------- ### Bind Generic Types Source: https://pythonnet.github.io/pythonnet/python.html Use subscript syntax to create concrete types from generic .NET types. ```python from System.Collections.Generic import Dictionary from System import * dict1 = Dictionary[String, String]() dict2 = Dictionary[String, Int32]() dict3 = Dictionary[String, Type]() ``` -------------------------------- ### Runtime Shutdown Source: https://pythonnet.github.io/clr-loader/reference.html Initiates the shutdown process for the CLR runtime. Final cleanup is typically handled by an `atexit` handler. ```python abstractmethod shutdown() → None ``` -------------------------------- ### PyObject Lifecycle and Type Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for managing the lifecycle of a PyObject and inspecting its Python type. ```APIDOC ## Dispose ### Description Explicitly releases the Python object represented by a PyObject instance. ## GetPythonType ### Description Returns the Python type of the object, equivalent to the Python expression: type(object). ## TypeCheck ### Description Returns true if the object is of type typeOrClass or a subtype. ### Parameters #### Request Body - **typeOrClass** (PyType) - Required - The type or class to check against. ``` -------------------------------- ### Pass a C# object to the Python runtime Source: https://pythonnet.github.io/pythonnet/_sources/dotnet.rst.txt Convert a C# object to a PyObject using ToPython() and set it within a Python scope for execution. ```csharp // create a person object Person person = new Person("John", "Smith"); // acquire the GIL before using the Python interpreter using (Py.GIL()) { // create a Python scope using (PyModule scope = Py.CreateScope()) { // convert the Person object to a PyObject PyObject pyPerson = person.ToPython(); // create a Python variable "person" scope.Set("person", pyPerson); // the person object may now be used in Python string code = "fullName = person.FirstName + ' ' + person.LastName"; scope.Exec(code); } } ``` -------------------------------- ### Variable Management Source: https://pythonnet.github.io/pythonnet/reference.html Functions for setting, removing, checking existence, and retrieving variables. ```APIDOC ## Set ### Description Add a new variable to the variables dict if it not exist or update its value if the variable exists. ### Method PyModule ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable. - **_value_** (object?) - Required - The value to set for the variable. ## Remove ### Description Remove a variable from the variables dict. ### Method PyModule ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable to remove. ## Contains ### Description Returns true if the variable exists in the module. ### Method bool ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable to check. ## Get ### Description Returns the value of the variable with the given name. ### Method PyObject ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable to retrieve. ### Throws KeyNotFoundException: Thrown when variable with the given name does not exist. ## TryGet ### Description Returns the value of the variable, local variable first. If the variable does not exist, return null. ### Method bool ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable to retrieve. - **_value_** (out PyObject?) - Required - Output parameter to store the retrieved value. ## Get ### Description Obtain the value of the variable of given name, and convert the result to a Managed Object of given type. If the variable does not exist, throw an Exception. ### Method T ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable to retrieve. ## TryGet ### Description Obtain the value of the variable of given name, and convert the result to a Managed Object of given type. If the variable does not exist, return false. ### Method bool ### Parameters #### Path Parameters - **_name_** (string) - Required - The name of the variable to retrieve. - **_value_** (out T?) - Required - Output parameter to store the retrieved value. ``` -------------------------------- ### Import CLR namespaces Source: https://pythonnet.github.io/pythonnet/python.html Treats CLR namespaces as Python packages for direct imports. ```python from System import String from System.Collections import * ``` -------------------------------- ### Function Execution Output Source: https://pythonnet.github.io/clr-loader/_sources/usage.rst.txt Expected console output after invoking the Test function. ```output Called Test in TestClass with testy mctestface, returning 16 Binary data: dGVzdHkgbWN0ZXN0ZmFjZQ== ``` -------------------------------- ### Inspect Method Signatures Source: https://pythonnet.github.io/pythonnet/_sources/python.rst.txt View the signature of a CLR method, including overloads, using its docstring (`__doc__`). Use the `help()` function to inspect managed classes. ```python from System import Environment print(Environment.GetFolderPath.__doc__) help(Environment) ``` -------------------------------- ### Python.NET Runtime Classes Source: https://pythonnet.github.io/pythonnet/_sources/reference.rst.txt Overview of the core C# classes provided by the Python.NET runtime for interacting with Python objects. ```APIDOC ## Python.NET Runtime API ### Description The Python.NET runtime provides a set of C# classes that map to Python types, allowing seamless integration between C# and Python code. ### Core Classes - **PythonEngine**: Manages the Python runtime environment. - **PyObject**: Base class for all Python objects. - **PyDict**: Wrapper for Python dictionary objects. - **PyTuple**: Wrapper for Python tuple objects. - **PyList**: Wrapper for Python list objects. - **PyInt**: Wrapper for Python integer objects. - **PyString**: Wrapper for Python string objects. - **PyType**: Wrapper for Python type objects. - **PyModule**: Wrapper for Python module objects. - **PyIter**: Wrapper for Python iterator objects. - **PyBuffer**: Wrapper for Python buffer objects. - **PyIterable**: Interface for Python iterable objects. - **PySequence**: Wrapper for Python sequence objects. - **PyNumber**: Wrapper for Python numeric objects. ``` -------------------------------- ### Module Import Functions Source: https://pythonnet.github.io/pythonnet/reference.html Functions for importing Python modules and their contents. ```APIDOC ## ImportAll ### Description Import all variables of the module into this module. ### Method void ### Parameters #### Path Parameters - **_module_** (PyModule) - Required - The module to import from. - **_module_** (PyObject) - Required - The module to import from. - **_dict_** (PyDict) - Required - The dictionary containing variables to import. ### Endpoint N/A (Function calls) ## Import ### Description Given a module or package name, import the module and return the resulting object. ### Method PyObject ### Parameters #### Path Parameters - **name** (string) - Required - Fully-qualified module or package name. ``` -------------------------------- ### PyBuffer Class Source: https://pythonnet.github.io/pythonnet/reference.html Provides methods for interacting with Python buffer objects. ```APIDOC ## IsContiguous ### Description Returns true if the memory defined by the view is C-style (order is ‘C’) or Fortran-style (order is ‘F’) contiguous or either one (order is ‘A’). Returns false otherwise. ### Method bool ### Parameters #### Path Parameters - **_order_** (BufferOrderStyle) - Required - C-style (order is ‘C’) or Fortran-style (order is ‘F’) contiguous or either one (order is ‘A’). ## GetPointer ### Description Get the memory area pointed to by the indices inside the given view. indices must point to an array of view->ndim indices. ### Method IntPtr ### Parameters #### Path Parameters - **_indices_** (long[]) - Required - An array of indices. ## FromContiguous ### Description Copy contiguous len bytes from buf to view. fort can be ‘C’ or ‘F’ (for C-style or Fortran-style ordering). ### Method void ### Parameters #### Path Parameters - **_buf_** (IntPtr) - Required - The source buffer. - **_len_** (long) - Required - The number of bytes to copy. - **_fort_** (BufferOrderStyle) - Required - The memory order ('C' or 'F'). ## ToContiguous ### Description Copy len bytes from view to its contiguous representation in buf. order can be ‘C’ or ‘F’ or ‘A’ (for C-style or Fortran-style ordering or either one). 0 is returned on success, -1 on error. ### Method void ### Parameters #### Path Parameters - **_buf_** (IntPtr) - Required - The destination buffer. - **_order_** (BufferOrderStyle) - Required - The memory order ('C', 'F', or 'A'). ## Write ### Description Writes a managed byte array into the buffer of a python object. This can be used to pass data like images from managed to python. ### Method void ### Parameters #### Path Parameters - **_buffer_** (byte[]) - Required - The managed byte array to write. - **_sourceOffset_** (int) - Required - The offset in the source buffer. - **_count_** (int) - Required - The number of bytes to write. - **_destinationOffset_** (nint) - Required - The offset in the destination buffer. ## Read ### Description Reads the buffer of a python object into a managed byte array. This can be used to pass data like images from python to managed. ### Method void ### Parameters #### Path Parameters - **_buffer_** (byte[]) - Required - The managed byte array to read into. - **_destinationOffset_** (int) - Required - The offset in the destination buffer. - **_count_** (int) - Required - The number of bytes to read. - **_sourceOffset_** (nint) - Required - The offset in the source buffer. ## Dispose ### Description Disposes the buffer. ### Method void ### Parameters None. ``` -------------------------------- ### PyObject Buffer Management Source: https://pythonnet.github.io/pythonnet/reference.html Methods for handling buffer access on Python objects. ```APIDOC ## GetBuffer ### Description Sends a request to the PyObject to fill in a buffer view. Successful calls must be paired with PyBuffer.Dispose(). ### Parameters - **flags** (int) - Required - Specifies the buffer request flags. ### Response - **return** (int) - Returns 0 on success, -1 on failure. ``` -------------------------------- ### Equals Method Source: https://pythonnet.github.io/pythonnet/reference.html Compares an object for equality with another object based on Python semantics. ```APIDOC ## Equals (object _o_) ### Description Return true if this object is equal to the given object. This method is based on Python equality semantics. ### Method bool ### Parameters #### Path Parameters - **_o_** (object) - Required - The object to compare with. ### Overrides object.Equals() ``` -------------------------------- ### GetBuffer Method Source: https://pythonnet.github.io/pythonnet/reference.html Retrieves a buffer for the object. ```APIDOC ## GetBuffer (PyBUF _flags_ , PyBUF _ = PyBUF.SIMPLE_) ### Description Retrieves a buffer for the object. ### Method PyBuffer ### Parameters #### Path Parameters - **_flags_** (PyBUF) - Required - The buffer flags. - **_** (PyBUF) - Optional - Defaults to PyBUF.SIMPLE_. ``` -------------------------------- ### Python.Runtime.PyDict API Source: https://pythonnet.github.io/pythonnet/reference.html Methods for interacting with Python dictionary objects. ```APIDOC ## PyDict Methods ### Description Provides methods to manipulate Python dictionary objects from .NET. ### Methods - PyDict() - HasKey() - Keys() - Values() - Items() - Copy() - Update() - Clear() - IsDictType() ``` -------------------------------- ### Runtime Class Source: https://pythonnet.github.io/clr-loader/reference.html Encapsulates the lifetime of a CLR (.NET) runtime. If the instance is deleted, the runtime will be shut down. ```APIDOC ## class clr_loader.Runtime ### Description Encapsulates the lifetime of a CLR (.NET) runtime. If the instance is deleted, the runtime will be shut down. ### Methods #### get_assembly ```python get_assembly(_assembly_path : str | PathLike[str]_) -> Assembly ``` ##### Description Get an assembly wrapper. This function does not guarantee that the respective assembly is or can be loaded. Due to the design of the different hosting APIs, loading only happens when the first function is referenced, and only then potential errors will be raised. #### info ```python abstractmethod info() -> RuntimeInfo ``` ##### Description Get configuration and version information. #### shutdown ```python abstractmethod shutdown() -> None ``` ##### Description Shut down the runtime as much as possible. Implementations should still be able to “reinitialize”, thus the final cleanup will usually happen in an `atexit` handler. ``` -------------------------------- ### Length Method Source: https://pythonnet.github.io/pythonnet/reference.html Returns the length of objects that support the Python sequence protocol. ```APIDOC ## Length () ### Description Returns the length for objects that support the Python sequence protocol. ### Method long ### Parameters None ``` -------------------------------- ### Retrieve Function Wrapper Source: https://pythonnet.github.io/clr-loader/_sources/usage.rst.txt Retrieves a callable function wrapper from the loaded assembly using class and method names. ```python function = assembly.get_function("Example.TestClass", "Test") function = assembly.get_function("Example.TestClass.Test") ``` -------------------------------- ### Python.Runtime.PyModule API Source: https://pythonnet.github.io/pythonnet/reference.html Methods for managing Python modules, execution, and scope. ```APIDOC ## PyModule Methods ### Description Provides functionality to import modules, execute Python code, and manage variables within a module scope. ### Methods - Reload() - Variables() - NewScope() - Import() - ImportAll() - Execute() - Eval() - Exec() - Set() - Remove() - Contains() - Get() - TryGet() ``` -------------------------------- ### Use Managed Indexers Source: https://pythonnet.github.io/pythonnet/_sources/python.rst.txt Call managed object indexers using standard Python indexing syntax. Overloaded indexers can be accessed using C#-like notation. ```python from System.Collections import Hashtable table = Hashtable() table["key 1"] = "value 1" items[0, 2] items[0, 2, 3] ``` -------------------------------- ### PyIterable Class Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for handling iterable Python objects in C#. ```APIDOC ## PyIterable Methods ### Description Allows any iterable Python object to be iterated over in C#. ### Methods - **GetEnumerator()**: Returns a new PyIter object for the object. Raises PythonException if not iterable. ``` -------------------------------- ### Define a compatible C# function signature Source: https://pythonnet.github.io/clr-loader/_sources/index.rst.txt Functions must match this specific signature to be callable from Python via clr-loader. ```csharp public static int Function(IntPtr buffer, int size) ``` -------------------------------- ### IsNone Method Source: https://pythonnet.github.io/pythonnet/reference.html Checks if an object is None. ```APIDOC ## IsNone () ### Description Return true if the object is None. ### Method bool ``` -------------------------------- ### Invoke Managed Function Source: https://pythonnet.github.io/clr-loader/_sources/usage.rst.txt Calls the retrieved function with a Python binary buffer. ```python result = function(b"testy mctestface") ``` -------------------------------- ### GetHashCode Method Source: https://pythonnet.github.io/pythonnet/reference.html Returns a hash code for the object based on Python's hash() function. ```APIDOC ## GetHashCode () ### Description Return a hashcode based on the Python object. This returns the hash as computed by Python, equivalent to the Python expression “hash(obj)”. ### Method int ### Overrides object.GetHashCode() ``` -------------------------------- ### Invoke Method Source: https://pythonnet.github.io/pythonnet/reference.html Invokes a callable Python object with provided arguments. ```APIDOC ## Invoke (params PyObject[] _args_) ### Description Invoke the callable object with the given arguments, passed as a PyObject[]. A PythonException is raised if the invocation fails. ### Method PyObject ### Parameters #### Path Parameters - **_args_** (PyObject[]) - Required - The arguments for the invocation. ``` ```APIDOC ## Invoke (PyTuple _args_) ### Description Invoke the callable object with the given arguments, passed as a Python tuple. A PythonException is raised if the invocation fails. ### Method PyObject ### Parameters #### Path Parameters - **_args_** (PyTuple) - Required - The arguments for the invocation as a Python tuple. ``` ```APIDOC ## Invoke (PyObject[] _args_ , PyDict? _kw_) ### Description Invoke the callable object with the given positional and keyword arguments. A PythonException is raised if the invocation fails. ### Method PyObject ### Parameters #### Path Parameters - **_args_** (PyObject[]) - Required - The positional arguments for the invocation. - **_kw_** (PyDict?) - Optional - The keyword arguments for the invocation. ``` ```APIDOC ## Invoke (PyTuple _args_ , PyDict? _kw_) ### Description Invoke the callable object with the given positional and keyword arguments. A PythonException is raised if the invocation fails. ### Method PyObject ### Parameters #### Path Parameters - **_args_** (PyTuple) - Required - The positional arguments for the invocation as a Python tuple. - **_kw_** (PyDict?) - Optional - The keyword arguments for the invocation. ``` -------------------------------- ### Sequence and Mapping Access Methods Source: https://pythonnet.github.io/pythonnet/reference.html Methods for accessing and modifying items in Python objects that support sequence or mapping protocols. ```APIDOC ## GetItem ### Description Returns the item at the given index or key for objects supporting sequence or mapping protocols. ## SetItem ### Description Sets the item at the given index or key to the specified value. ## DelItem ### Description Deletes the item at the given key for objects supporting sequence or mapping protocols. ``` -------------------------------- ### pythonnet.unload() Source: https://pythonnet.github.io/pythonnet/pyreference.html Unloads the runtime and shuts down Python.NET. ```APIDOC ## POST pythonnet.unload() ### Description Explicitly unload a loaded runtime and shut down Python.NET. ```