每当我加载它时,C# – cc3260mt.dll都会抛出ArithmeticException

我有一个WPF应用程序,我必须加载DLL cc3260mt.dll我通过使用LoadLibrary()调用它,但无论出于何种原因我得到一个ArithmeticException。

这是我的代码的样子:

 public partial class MainWindow : Window { [DllImport("kernel32.dll")] static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] static extern IntPtr FreeLibrary(IntPtr hModule); public MainWindow() { InitializeComponent(); try { string cc3260mtPath = "dll/cc3260mt.dll"; IntPtr cc3260Link = LoadLibrary(cc3260mtPath); } catch (Exception ex) { Console.WriteLine("ERROR : " + ex.Message); } } // <-- This is where I get the Exception. } 

当我逐步运行我的代码时,我可以清楚地看到当我离开MainWindow()类时出现exception。
你们有什么想法让我这个例外吗?

这是旧的Borland C或C ++程序的C运行时支持库。 是的,它通常与.NET代码非常不兼容,特别是WPF,它重新编程浮点单元控制寄存器。 它启用硬件exception,在浮点运算失败时触发。 在WPF中特别有问题,因为喜欢使用Double.NaN很多。 这会产生FPUexception,CLR会拦截它并将其重新引发为ArithmeticException。

您必须撤消此DLL所执行的操作并恢复FPU控制字。 这是有问题的,.NET不允许您直接访问这样的硬件。 但是你可以使用一个技巧,CLR在处理exception时自动重新编程FPU。 所以你可以故意生成一个exception并抓住它。 像这样:

  IntPtr cc3260Link = LoadLibrary(cc3260mtPath); try { throw new Exception("Ignore this please, resetting the FPU"); } catch (Exception ex) {} 

请注意这一点的结果,您现在将运行本机代码,而不会通常依赖它。 也许那会奏效。