アンマネージDLLの動的呼び出し C#版

naohiro19
記事: 256
登録日時: 14年前
住所: 愛知県

アンマネージDLLの動的呼び出し C#版

投稿記事 by naohiro19 » 10年前

C# - DllImportちゃんどいて!そいつ読み込めない! - QiitaにあるUnManagedDllクラスを使うとこんなに簡単に書くことができます。

以下のプログラムはUser32.dllにある「MessageBox」関数を呼び出すサンプルプログラムです。

CODE:

using MMFrame.Diagnostics;

public class User32 : UnManagedDll
{
	private class Functions
	{
 		[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet = CharSet.Ansi)] 
		public delegate int MessageBox(IntPtr hwnd, string text, string caption, uint type);
	}

	public User32(string dllPath) : base(dllPath) {}

	public int MessageBox(IntPtr hwnd, string text, string caption, uint type)
	{
		return GetProcAddress()(hwnd, text, caption, type);
	}
}


//使う側
using(User32 user32 = new User32("User32.dll"))
{
	user32.MessageBox(IntPtr.Zero, "テキスト", "キャプション", 0x4);
}
Windows APIの型と.NET Frameworkにおける型は以下の知恵袋ノートのように対応する必要があります。
http://note.chiebukuro.yahoo.co.jp/detail/n350146
► スポイラーを表示
最後に編集したユーザー naohiro19 on 2015年8月16日(日) 08:28 [ 編集 5 回目 ]

コメントはまだありません。