栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从C#构建Python脚本和调用方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从C#构建Python脚本和调用方法

有点。您不能直接从C#代码访问Python方法。除非您正在使用C#4.0和dynamic关键字,否则您将非常非常特别;)。但是,您可以将IronPython类编译为DLL,然后在C#中使用IronPython托管来访问方法(这适用于IronPython
2.6和.NET 2.0)。

创建一个这样的C#程序:

using System;using System.IO;using System.Reflection;using IronPython.Hosting;using Microsoft.scripting.Hosting;// we get access to Action and Func on .Net 2.0 through Microsoft.scripting.Utilsusing Microsoft.scripting.Utils;namespace TestCallIronPython{    class Program    {        public static void Main(string[] args)        { Console.WriteLine("Hello World!"); scriptEngine pyEngine = Python.CreateEngine(); Assembly myclass = Assembly.LoadFile(Path.GetFullPath("MyClass.dll")); pyEngine.Runtime.LoadAssembly(myclass); scriptScope pyScope = pyEngine.Runtime.importModule("MyClass"); // Get the Python Class object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass")); // Invoke a method of the class pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]); // create a callable function to 'somemethod' Action SomeMethod2 = pyEngine.Operations.GetMember<Action>(MyClass, "somemethod"); SomeMethod2(); // create a callable function to 'isodd' Func<int, bool> IsOdd = pyEngine.Operations.GetMember<Func<int, bool>>(MyClass, "isodd"); Console.WriteLine(IsOdd(1).ToString()); Console.WriteLine(IsOdd(2).ToString()); Console.Write("Press any key to continue . . . "); Console.ReadKey(true);        }    }}

创建一个普通的Python类,如下所示:

class MyClass:    def __init__(self):        print "I'm in a compiled class (I hope)"    def somemethod(self):        print "in some method"    def isodd(self, n):        return 1 == n % 2

编译它(我使用SharpDevelop),但是该

clr.CompileModules
方法也应该起作用。然后将已编译
MyClass.dll
的文件推入已编译的C#程序所在的目录中并运行它。您应该得到以下结果:

Hello World!I'm in a compiled class (I hope)in some methodin some methodTrueFalsePress any key to continue . . .

这包含了Jeff的更直接的解决方案,该解决方案省去了创建和编译一个小的Python“存根”的麻烦,并且还展示了如何创建可访问Python类中的方法的C#函数调用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611845.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号