C#|アンマネージドDLLを動的にロードする

アンマネージドDLLを遅延バインディングで動的にロードするクラス

using System;
using System.Runtime.InteropServices;

public class UnManagedDll :IDisposable {
    [DllImport("kernel32")]
    static extern IntPtr LoadLibrary(string lpFileName);
    [DllImport("kernel32")]
    static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
    [DllImport("kernel32")]
    static extern bool FreeLibrary(IntPtr hModule);

    IntPtr moduleHandle;

    public UnManagedDll(string lpFileName) {
        moduleHandle = LoadLibrary(lpFileName);
    }

    public IntPtr ModuleHandle {
        get {
            return moduleHandle;
        }
    }

    public T GetProcDelegate<T>(string method) where T :class {
        IntPtr methodHandle = GetProcAddress(moduleHandle, method);
        T r = Marshal.GetDelegateForFunctionPointer(methodHandle, typeof(T)) as T;
        return r;
    }

    public void Dispose() {
        FreeLibrary(moduleHandle);
    }
}

 

以下の様に使用する。

using System;

class Program {
    delegate int MessageBoxADelegate(IntPtr hWnd, string lpText, string lpCaption, uint uType);

    static void Main(string[] args) {
        using(UnManagedDll user32Dll = new UnManagedDll("user32.dll")) {
            MessageBoxADelegate MessageBoxA =
                user32Dll.GetProcDelegate<MessageBoxADelegate>("MessageBoxA");

            MessageBoxA(IntPtr.Zero, "テキスト", "キャプション", 0);
        }
    }
}

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください