最終更新:2017-12-15 (金) 19:05:44 (2314d)  

動的PInvoke
Top / 動的PInvoke

Platform Invoke、P/Invoke、プラットフォーム呼び出し

宣言

//DLLモジュールをマップ
[DllImport("kernel32",
    EntryPoint = "LoadLibrary",
    SetLastError = true,
    CharSet = CharSet.Auto,
    ExactSpelling = false)]
private extern static IntPtr LoadLibrary(
    [MarshalAs(UnmanagedType.LPTStr)]string lpFileName);
//マップを解除
[DllImport("kernel32",
    EntryPoint = "FreeLibrary",
    SetLastError = true,
    ExactSpelling = true)]
private extern static bool FreeLibrary(
    IntPtr hModule);
//関数のアドレスを取得
[DllImport("kernel32",
    EntryPoint = "GetProcAddress",
    SetLastError = true,
    CharSet = CharSet.Ansi,
    ExactSpelling = true)]
private extern static IntPtr GetProcAddress(
    IntPtr hModule,
    [MarshalAs(UnmanagedType.LPStr)]string lpProcName);

//書庫操作一般
[UnmanagedFunctionPointer(
    CallingConvention.Winapi,
    CharSet = CharSet.Ansi)]
//デリゲートを宣言
private delegate int ExecuteDelegate(
    IntPtr _hwnd,
    [MarshalAs(UnmanagedType.LPStr)]string _szCmdLine,
    [MarshalAs(UnmanagedType.LPStr)]StringBuilder _szOutput,
    uint _dwSize);

呼び出し

//DLLをロード
IntPtr hmod = LoadLibrary(dllName);

//関数ポインタを取得
IntPtr funcAddr = GetProcAddress(hmod, funcName);

//デリゲートを設定
ExecuteDelegate execute =
(ExecuteDelegate)Marshal.GetDelegateForFunctionPointer(
funcAddr, typeof(ExecuteDelegate));

//デリゲートを呼び出す
int ret = execute(IntPtr.Zero,
string.Format("x \"{0}\" \"{1}\" *", archiveFile, extractTo),
null, 0);

リンク