アンマネージドDLLの読み込み
最終更新:
atachi
基本設計
C++やその他の言語で作成されたDLLは、CLIによる実装ではない(アンマネージドDLL)です。
DllImport属性を使ってインポートするDLLを選ぶ。シグネチャはAPIのリファレンスマニュアルを参考してください。
WindowsAPIで使用されている型とC#での型の対応表は次の項目を参照してください。
[DllImport("user32.dll")]
extern static int GetWindowText(IntPtr hWnd,StringBuilder lpStr,int nMaxCount);型変換ルール
| WindowsAPIの型名 | C#および.NETの型名 | ||
| Windows API | C | C# プリミティブ | .NET Framework |
| HWND | void * | → | System.IntPtr |
| WPARAM | unsigned int | uint | System.UInt32 |
| LPARAM | long | int | System.Int32 |
| LRESULT | long | int | System.Int32 |
| HANDLE | void * | → | System.IntPtr |
| BYTE | unsigned char | byte | System.Byte |
| SHORT | short | short | System.Int16 |
| WORD | unsigned short | ushort | System.UInt16 |
| INT | int | int | System.Int32 |
| LONG | long | ||
| UINT | unsigned int | uint | System.UInt32 |
| DWORD | unsigned long | ||
| ULONG | unsigned long | ||
| BOOL | int | bool | System.Boolean |
| CHAR | char | char | System.Char |
| LPSTR | char * | → | System.Text.StringBuilder |
| LPWSTR | wchar_t * | ||
| LPCSTR | const char * | string | System.String |
| LPCWSTR | const wchar_t * | ||
| FLOAT | float | float | System.Single |
| DOUBLE | double | double | System.Double |
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);
}
}
}



