Click here to Skip to main content
12,625,547 members (36,915 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


23 bookmarked

How to release an unmanaged library loaded into managed .NET code

, 4 Dec 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Explains how to release an unmanaged library loaded into managed .NET code


I had found this article on how to release a DLL library already loaded into a process using P-Invoke. It uses the LoadLibrary() and FreeLibrary() WinAPI calls to achieve this.

And what is wrong with it?

It forces to unload all instances of the DLL library currently loaded within the process. Which means, that in the case you have more than one instance of the class using these external functions, all these will stop working!

And that is not all - you cannot use this DLL in the same application domain again after unloading.


The solution is a pretty simple one, but I have to say that it wasn't very obvious to me at the beginning. You can use P-Invoke to import the following standard WinAPI functions for dynamical function loading:

  • LoadLibrary()
  • FreeLibrary()
  • GetProcAddress()

We will use the following wrapping class:

internal static class UnsafeMethods
    [DllImport("kernel32.dll", SetLastError = true)]
    internal extern static IntPtr LoadLibrary(string libraryName);
    [DllImport("kernel32.dll", SetLastError = true)]
    internal extern static bool FreeLibrary(IntPtr hModule);
    [DllImport("kernel32.dll", SetLastError = true)]
    internal extern static IntPtr GetProcAddress(IntPtr hModule, string procName);

We also need signatures of the imported functions - we will convert them into delegates (the following ones come from the sample project):

// int multiply(int value1, int value2);
private delegate int MultiplyDelegate(int value1, int value2);
// int str2int(const char *input);
private delegate int Str2IntDelegate([MarshalAs(UnmanagedType.LPStr)]string source);

Now we can implement our class calling the external DLL functionality with the IDisposable interface so it will automatically release the used DLL library when it goes out-of-scope or when it is finalized (in the example project are two functions which we will publish as Multiply() and Str2Int()).

public class ExternalHelpers: IDisposable
    #region Private members
    private IntPtr _libraryHandle;
    private MultiplyDelegate _multiply;
    private Str2IntDelegate _str2Int;

    #region External functions delegates
    // int multiply(int value1, int value2);
    private delegate int MultiplyDelegate(int value1, int value2);
    // int str2int(const char *input);
    private delegate int Str2IntDelegate([MarshalAs(
                     UnmanagedType.LPStr)]string source);

    public ExternalHelpers()
        // dynamically load DLL using WinAPI
        _libraryHandle = UnsafeMethods.LoadLibrary(@"testing.dll");

        if (_libraryHandle == IntPtr.Zero)
        // import functions as delegates using GetProcAddress
        _multiply = LoadExternalFunction<MultiplyDelegate>(@"multiply");
        _str2Int = LoadExternalFunction<Str2IntDelegate>(@"str2int");

    public int Multiply(int value1, int value2)
        // call method using delegate
        return _multiply(value1, value2);

    public int Str2Int(string source)
        // call method using delegate
        return _str2Int(source);

    public void Dispose()



    #region Private helper methods
    private Delegate LoadExternalFunction<T>(string functionName)
        where T: class 
        // load function pointer
        IntPtr functionPointer = 
          UnsafeMethods.GetProcAddress(_libraryHandle, functionName);

        if (functionPointer == IntPtr.Zero)
        // Marshal to requested delegate
        return Marshal.GetDelegateForFunctionPointer(functionPointer, typeof(T)) as T;

    private void Dispose(bool disposing)
        if (disposing)
            _multiply = null;
            _str2Int = null;

        if (_libraryHandle != IntPtr.Zero)
            if (!UnsafeMethods.FreeLibrary(_libraryHandle))
            _libraryHandle = IntPtr.Zero;

And finally - we can use it:

static void Main(string[] args)
    using(ExternalHelpers e = new ExternalHelpers())
        const int value1 = 2;
        const int value2 = 3;
        const string strValue = "345";

        Console.WriteLine("{0} * {1} = {2}", 
                value1, value2, e.Multiply(value1, value2));
        Console.WriteLine("{0} => {1}", 
                strValue, e.Str2Int(strValue));


Looks easy? Yes it is :-)



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Team Leader NCR
Czech Republic Czech Republic
I'm software developer since 1996. I started with assembler on Intel 8051 CPUs, during years I was interested in C, C++, Sybase PowerBuilder, PHP, Sybase Anywhere Database, MSSQL server and multiplatform development.

Currently I'm developing in C++ and C# (this is my favorit and I spent some time with MCPD achievement). I'm also interested in design patterns.

You may also be interested in...

Comments and Discussions

Suggestionreturn type of method LoadExternalFunctions Pin
Markus6414-Feb-12 1:56
memberMarkus6414-Feb-12 1:56 
GeneralRe: return type of method LoadExternalFunctions Pin
voloda214-Feb-12 21:42
membervoloda214-Feb-12 21:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161128.1 | Last Updated 4 Dec 2014
Article Copyright 2011 by voloda2
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid