Unmanaged DLL dynamisch laden

Links

Code

// LoadLibrary, GetProcAddress, FreeLibrary aus der kernel32.dll laden
static class DLLBaseFunc
{
        [DllImport("kernel32.dll")]
        public static extern IntPtr LoadLibrary(string dllToLoad);

        [DllImport("kernel32.dll")]
        public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

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

class Program
{
    // delegat-Funktion definieren, die eine DLL-Funktion abbildet
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    private delegate int AddFct(int a, int b);

    static void Main(string[] args)
    {
        // DLL laden
        IntPtr pDll = DLLBaseFunc.LoadLibrary("c:\\temp\\meine.dll");

        if (pDll != IntPtr.Zero)
        {
            // Funktionszeiger holen
            IntPtr pAdd = DLLBaseFunc.GetProcAddress(pDll, "Add");
            
            if (pAdd != IntPtr.Zero)
            {
                // Funktionszeiger in delegat-Typ wandeln
                AddFct Add = (AddFct)Marshal.GetDelegateForFunctionPointer(pAdd, typeof(AddFct));

                // delegat-Funktion (DLL-Funktion) aufrufen
                int theResult = Add(10, 20);
            }
            
            // DLL entladen
            if (DLLBaseFunc.FreeLibrary(pDll) == false)
            {
                // error
            }
        }
    }
}