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

Build Python scripts and call methods from C#

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

Build Python scripts and call methods from C#

Sort of. You cannot access the Python methods directly from C# pre. Unless
you are playing with C# 4.0 and the dynamic keyword or you are very, very
special ;). However, you can compile an IronPython class to a DLL and then use
IronPython hosting in C# to access the methods (this is for IronPython 2.6 and
.NET 2.0).

Create a C# program like this:

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);        }    }}

Make a trivial Python class like this:

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

Compile it (I use SharpDevelop)
but the

clr.CompileModules
method should also work. Then shove the compiled
MyClass.dll
into the directory where the compiled C# program lives and run
it. You should get this as the result:

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

This incorporates Jeff’s more direct solution that eliminates having to create
and compile a small Python ‘stub’ and also shows how you can create C#
function calls that access the methods in the Python class.



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

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

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