我开始使用 IronPython 开发 Excel-DNA 插件,并使用一些 C# 作为调用 IronPython 的包装器。在 Excel-DNA 开发人员的慷慨帮助下,我已经解决了启动和运行示例的一些初始问题,但现在我正在尝试在 SharpDevelop 中调试插件,但遇到了一些问题。由于我对其中的大部分内容完全陌生,我不确定这是否是 SharpDevelop、.NET、Excel-DNA 或 IronPython 的问题。
我在一个解决方案中创建了两个项目,一个是 C# 类库。另一个是python类库。我按照在博客上找到的教程设置项目以进行调试。我能够逐步完成 C# 代码的前几行,这就是进步,但是当我到达以下行时:
pyEngine.Runtime.LoadAssembly(myclass);
我得到一个例外:
“无法加载文件或程序集 'Microsoft.Dynamic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' 或其依赖项之一。找到的程序集的清单定义与程序集引用不匹配。(来自 HRESULT 的异常:0x80131040 )"
但我很确定我已将 Microsoft.Dynamic 引用添加到我的项目中。它是 1.1.0.20 版本。这包含在 IronPython 发行版中,但也包含在我计算机上的另一个位置。我尝试设置对两者的引用,但它们都具有相同的版本号并且文件大小似乎相同。两者都不起作用。我需要版本 1.0.0.0 还是我做错了什么?我真的不明白为什么任何 pyEngine(由 Python.CreateEngine() 返回的 ScriptEngine)会尝试加载与发行版中包含的版本不同的版本。
代码如下。如果您需要任何其他信息,请告诉我。
MyAddin.cs
/*
Added these references all as Local Copies - probably not necessary?
System.Windows.Forms
Microsoft.CSharp
ExcelDna.Integration (from Excel-DNA distribution folder)
IronPython (from IronPython folder)
IronPython.Modules (from IronPython folder)
Microsoft.Dynamic (from IronPython folder)
Microsoft.Scripting (from IronPython folder)
Microsoft.Scripting.Metadata (from IronPython folder)
mscorlib (I don't really know why I added this, but it was one of the references in my IronPython class library)
MyClass (this is the reference to my IronPython class - I checked to see that it gets copied in every time I rebuild the solution and it does)
These were automatically added by SharpDevelop when I created the project.
System
System.Core
System.Windows.Forms
System.Xml
System.Xml.Linq
*/
using System;
using System.IO;
using System.Windows.Forms;
using ExcelDna.Integration;
using System.Reflection;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
public class MyAddIn : IExcelAddIn
{
public void AutoOpen()
{
try
{
string xllDirectory = Path.GetDirectoryName(@"C:/Users/myname/Documents/SharpDevelop Projects/IronPythonExcelDNATest/MyAddIn/bin/Debug/");
string dllPath = Path.Combine(xllDirectory,"MyClass.dll");
Assembly myclass = Assembly.LoadFile(dllPath);
ScriptEngine pyEngine = Python.CreateEngine();
pyEngine.Runtime.LoadAssembly(myclass);
ScriptScope pyScope = pyEngine.Runtime.ImportModule("MyClass");
object myClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass"));
IronTest.AddSomeStuff = pyEngine.Operations.GetMember<Func<double, double,double>>(myClass, "AddSomeStuff");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void AutoClose()
{
}
}
public class IronTest
{
public static Func<double, double, double> AddSomeStuff;
public static double TestIPAdd(double val1, double val2)
{
try
{
return AddSomeStuff(val1, val2);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return double.NaN;
}
}
}
我的类.py
class MyClass:
def __init__(self):
pass
def AddSomeStuff(self,x,y):
return x + y