有点。您不能直接从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.Utils
using 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 method
in some method
True
False
Press any key to continue . . .
这包含了Jeff的更直接的解决方案,该解决方案省去了创建和编译一个小的Python“存根”的麻烦,并且还展示了如何创建可访问Python类中的方法的C#函数调用。