Integration of python in C# Application

混江龙づ霸主 提交于 2019-11-29 04:09:42
cdjc

IronPython is what you want. It compiles to .NET bytecode. You can reasonably easily call python code from another .NET language (and the other way around). IronPython is supported in Visual Studio too, I think.

Python scripts can be executed from C# with IronPython.

    var ipy = Python.CreateRuntime();
    dynamic test = ipy.UseFile("Test.py");
    test.Simple();

See also:

http://putridparrot.com/blog/hosting-ironpython-in-a-c-application/

and

https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/

You can use IronPython's ScriptScope.GetVariable to get the actual function and then you can call it like a C# function. Use it like this:

C# code:

var var1, var2 = ...
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(@"C:\test.py", scope);
dynamic testFunction = scope.GetVariable("test_func");
var result = testFunction(var1,var2);

Python code:

def test_func(var1,var2):
    ...do something...

Took me a while to finally figure it out, and it's quite simple.. And IronPython is free and pretty easy to use. Hope this helps :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!