Today I will show you how can use Dynamic Language Runtime with IronPython.
The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. see the online documentation.
I use Visual Studio 2019 and .NET Framework 4.7.2 with my Console C# project named DynamicLanguageRuntime_001.
Let’s install the package with Visual Studio by open the console using the main menu: Tools – NuGet Package Manager – Package Manager Console command.
1 2 3 | PM> Install-Package DynamicLanguageRuntime Package 'DynamicLanguageRuntime.1.2.3' already exists in project 'DynamicLanguageRuntime_001' Time Elapsed: 00:00:01.2208674 |
Use Solution Explorer use right-click on References item from your project and use Add Reference …
Into the new window dialog named Reference Manager on the Assemblies – Framework uses the edit box to search IronPython.
Then use the checkbox to select these two options: IronPython and IronPython.Modules.
See the next screenshot:
I create a simple source code with comments to see how this working.
The source code for my project is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IronPython.Hosting; using IronPython.Runtime; using IronPython; using Microsoft.Scripting.Hosting; using Microsoft.Scripting; namespace DynamicLanguageRuntime_001 { class Program { static void Main(string[] args) { // create python engine ScriptEngine engine = Python.CreateEngine(); // get and add paths to enfine var python_search_paths = engine.GetSearchPaths(); python_search_paths.Add(@"C:\Program Files\IronPython 2.7\Lib"); engine.SetSearchPaths(python_search_paths); // create a scope ScriptScope scope = engine.CreateScope(); // using CreateScriptSourceFromString engine.CreateScriptSourceFromString("print '... simple example with ironpython and C#'").Execute(); // using Execute engine.Execute("print ' by catafest!'", scope); // using ExecuteFile engine.ExecuteFile(@"D:\Projects\Python\testing\test_webpage_001.py", scope); dynamic testFunction = scope.GetVariable("GetFriends"); var result = testFunction(); } } } |
The last step is to build and run it.