Question

I have a WPF Application, and I must load the DLL cc3260mt.dll I call it by using LoadLibrary(), but for whatever reason I am getting an ArithmeticException.

Here is what my code looks like :

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.
}

When I run my code step by step, I can clearly see that the exception appears when I get out of my MainWindow() class.
Do you guys have any idea what gets me this exception ?

Était-ce utile?

La solution

That is the C runtime support library for old Borland C or C++ programs. And yes, it does something that's very incompatible with .NET code in general, and WPF in particular, it reprograms the floating point unit control register. It enables hardware exceptions, triggered when a floating point operation fails. Particularly problematic in WPF because is likes to use Double.NaN a lot. Which generates an FPU exception, the CLR intercepts it and re-raises it as an ArithmeticException.

You will have to undo what this DLL did and restore the FPU control word. This is problematic, .NET doesn't give you direct access to the hardware like that. There is however a trick you can use, the CLR automatically reprograms the FPU when it handles an exception. So you can intentionally generate an exception and catch it. Like this:

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

Do note the consequence of this, you'll now have the native code running without the exceptions it normally relies on. Maybe that will work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top