Unloading Or Releasing an Unmanaged Dll When Using DllImport???

I am trying to figure out how to unload and Unmanaged Dll that was originally loaded with DllImport, but I have not had any luck so far.

Let me explain the reason for wanting to do this.  I have an unmanaged Dll containing resources.  I load this dll and check it for a specified value.  If that value does not exist, I want to update the resources.  The problem I have run into is that the unmanaged Dll is not being unloaded after I check for the specified value and therefore I cannot update the Dll resources.

Can I use Dispose to unload the unmanaged Dll   If so, how   If I cannot unload the unmanaged Dll are there any other suggestions on how to update the Dll resources

Any help would be appreciated.



Answer this question

Unloading Or Releasing an Unmanaged Dll When Using DllImport???

  • isunshine

    Thanks!!  That is exactly what I needed.  I was using LoadLibrary and FreeLibrary, but I was only calling FreeLibrary once.  Now that I am calling it in a loop as suggested in the blog you posted, the unmanaged DLL is being released and I am able to update it.
  • Dave Elliott Msdn

    I'm sure I've read that unmanaged libraries are loaded in the same way as domain neutral assemblies so I don't think that using a separate app domain will help.  As Michael says, I think your best chance is to have a play with LoadLibrary().

    Cheers,

    Bill

  • Antony Nguyen

    Hi,
    Use GetModuleHandle and FreeLibrary which are WIN32 APIs.
    The following link might be good pointer for you,
    http://blogs.msdn.com/robgruen/archive/2004/11.aspx

    HTH,

  • RickyBaaa

    Once the dll is loaded it can't be unloaded.  The only way to work around this issue is to load the dll into a secondary AppDomain and then unload the AppDomain once you're done.  Even then I'm not 100% sure that the unmanaged dll will be unloaded.  It probably depends on how the CLR shares unmanaged DLLs across AppDomains.  Unfortunately setting up and tearing down an AppDomain can be expensive so if this is something you need to do often then you're going to take a noticeable performance hit.

    An alternative, since you really only care about the resources, would be to manually load the DLL using LoadLibrary(), doing your work and then calling FreeLibrary().  This sidesteps the CLR loading the binary completely.  I'm not sure if it'll work for your case however.

    Michael Taylor - 12/1/05

  • Unloading Or Releasing an Unmanaged Dll When Using DllImport???