C# FreeLibrary() ArithmeticException

2019-08-31 12:43发布

问题:

I am using Visual Studio 2012 and a C# WPF Application.
I am actually trying to load 3 DLLs and then unload them. I have to do this because I cannot add those DLL as a reference to my C# project.
The problem is that I keep getting an ArithmeticException with those DLL. I need all of them, because dll1 needs dll2 and dll3 to run properly.
I have been executed my code step by step, and here is what happend :
My LoadLibrary() do found all the DLLs. Once I get to the FreeLibrary(), there is no error, but at the end of my code (exactly, when going out of MainWindow()) I get an ArithmeticException.

I have already tried putting each of my FreeLibrary() in separated if to see if one of them were not executed correctly, without any success.
I have also put each of my FreeLibrary() in a while to be sure that the ref count goes to 0, but there I am having another interesting thing : my application get lock on my last Dll. It does the first and second while correctly, but get stuck to the last one. I have to manually stop the application, and I am not able to continue my step by step, and there is not a single error or whatever on the stacks of the threads.

Here is my code :

  public partial class MainWindow : Window
  {
    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    static extern bool FreeLibrary(IntPtr hModule);

    public MainWindow()
    {
        InitializeComponent();
        try
        {
            string dll1Path = "dll/dll1.dll";
            string dll2Path = "dll/dll2.dll";
            string dll3Path = "dll/dll3.dll";

            IntPtr dll3Link = LoadLibrary(dll3Path);
            IntPtr dll2Link = LoadLibrary(dll2Path);
            IntPtr dll1Link = LoadLibrary(dll1Path);

            if(FreeLibrary(dll3Link) == true && FreeLibrary(dll2Link) == true && FreeLibrary(dll1Link) == true)
                 Console.WriteLine("All DLL have been unloaded");
            else
                 Console.WriteLine("One or more DLL were not unloaded properly");

            }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR : " + ex.Message); 
        }

    }

}

回答1:

At what point do you get the exception?

You can call File.Exists(dll1Path) to check if your DLL exists. Maybe threre's your problem



回答2:

You code works just fine, for me. where is you dll/dll1.dll, are they in your bin/debug?