简体   繁体   中英

Invoking IronPython function from C# after IronPython runtime was disposed

Suppose we have the following code in IronPython:

def hello():
    print "Hello from Python"

We call function hello() in the following C# code:

    private static void GetPythonFunction()
    {
        ScriptRuntime scriptRuntime = IronPython.Hosting.Python.CreateRuntime();
        ScriptScope scope = scriptRuntime.ExecuteFile(@"Python\helloFunc.py");
        Action hello = scope.GetVariable<Action>("hello");
        hello();
        scriptRuntime.Shutdown();
        hello(); // after IronPython runtime was disposed
    }

Which gives us result:

Hello from Python
Hello from Python

Why the second call hello() works twice even though the runtime environment was disposed?

Shutdown doesn't actually terminate the runtime, it just runs some cleanup routines. Things might be in a strange state afterwards, though, so there's no guarantee anything will work.

Plus, hello probably (I don't recall the exact details of how the delegates are created) has references to the runtime and engine keeping everything from being GC's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM