Link to home
Start Free TrialLog in
Avatar of JonathanAyres
JonathanAyres

asked on

Free a DLL Reference (equivalent to FreeLibrary).

I have referenced a legacy DLL using the DLLImport mechanism. Is it possible to manually free the reference after I have used it? (i.e. equivalent to using Win 32 FreeLibrary()).

Alternatively, if I could use LoadLibrary() & FreeLibrary () instead of the import facility, that would do fine

Explanation:

The C# code calls the DLL function to determine whether a particular application is running. If the DLL reference is held, the application then refuses to start.
Avatar of saar2
saar2

Paste this in your code and will let you call FreeLibrary to unload the DLL.

using System.Runtime.InteropServices;
[DllImport ("Kernel32")]
public static extern bool FreeLibrary(IntPtr hModule);

[DllImport ("Kernel32")]
public static extern IntPtr GetModuleHandle(string lpModuleName);


As you don't have the module handler for FreeLibrary you'll have to get it by calling GetModuleHandle (pass you dll filename as a parameter).

Please let me know if this works.

I don't think you want to use LoadLibrary as you probably have problems with GetProcAddress.

Good luck.

Saar Carmi
Israel .Net Developer
saar@bigfoot.com
Avatar of JonathanAyres

ASKER

Thanks Saar

That seems to work but has a rather significant drawback. Once I have freed the library, I can no longer call the method - it seems that the DLLImport facility does not expect to have its library freed and has no reload facility.

Obviously, if I could use LoadLibrary it would allow me to get round this but as you point out, there will be problems with GetProcAddress (or at least using the address that it returns.

Jonathan
We cannot be certain that the DllImport won't call GetProcAddress again - until we try that.

Saar
It sounds like the functions in your dll are locking the application you are wanting to run.  Just .net holding a reference to the dll and its functions should in no way lock another app from running.  I would check the dll code first.
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
PAQ/No Refund
Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TheAvenger
EE Cleanup Volunteer
ASKER CERTIFIED SOLUTION
Avatar of Computer101
Computer101
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial