Instantiating a python class in C#

后端 未结 4 1343
情话喂你
情话喂你 2020-11-28 02:42

I\'ve written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I\'ve migrated the class to IronPython, created

4条回答
  •  有刺的猬
    2020-11-28 03:10

    I am updating the above example provided by Clever Human for compiled IronPython classes (dll) instead of IronPython source code in a .py file.

    # Compile IronPython calculator class to a dll
    clr.CompileModules("calculator.dll", "calculator.py")
    

    C# 4.0 code with the new dynamic type is as follows:

    // IRONPYTHONPATH environment variable is not required. Core ironpython dll paths should be part of operating system path.
    ScriptEngine pyEngine = Python.CreateEngine();
    Assembly myclass = Assembly.LoadFile(Path.GetFullPath("calculator.dll"));
    pyEngine.Runtime.LoadAssembly(myclass);
    ScriptScope pyScope = pyEngine.Runtime.ImportModule("calculator");
    dynamic Calculator = pyScope.GetVariable("Calculator");
    dynamic calc = Calculator();
    int result = calc.add(4, 5);
    

    References:

    1. Using Compiled Python Classes from .NET/CSharp IP 2.6
    2. Static Compilation of IronPython scripts

提交回复
热议问题