C/C++でのDLL関数のプロトタイプ宣言
int MessageBox( HWND hWnd, // オーナーウィンドウのハンドル LPCTSTR lpText, // メッセージボックス内のテキスト LPCTSTR lpCaption, // メッセージボックスのタイトル UINT uType // メッセージボックスのスタイル );
C#から P/Invokeで呼び出すときのプロトタイプ
using System.Runtime.InteropServices; public class ○○Class [ [DllImport("user32.dll")] public static extern int MessageBox( int hWnd, String text, String caption, uint type ); }
dllでの関数名とC#での関数名を変えたい場合。
using System.Runtime.InteropServices; public class ○○Class [[DllImport("user32.dll", EntryPoint="MessageBox")] public static extern int MessageBoxFunction( int hWnd, String text, String caption, uint type ); }
StringをAnsi文字列に変換
using System.Runtime.InteropServices; public class ○○Class [[DllImport("user32.dll", EntryPoint="MessageBoxA",CharSet=CharSet.Ansi)] public static extern int MessageBox( int hWnd, String text, String caption, uint type ); }
StringをUnicode文字列に変換
using System.Runtime.InteropServices; public class ○○Class [[DllImport("user32.dll", EntryPoint="MessageBoxW",CharSet=CharSet.UniCode)] public static extern int MessageBox( int hWnd, String text, String caption, uint type ); }
HRESULTを返すアンマネージメソッドのプロトタイプ
HRESULT SHAutoComplete( _In_ HWND hwndEdit, DWORD dwFlags );
HRESULT(またはretval)を返す関数のエラーを対応する例外に自動で変更する。
public enum SHAutoCompleteFlags { SHACF_DEFAULT = 0x00000000, SHACF_FILESYSTEM = 0x00000001 } [DllImportAttribute("shlwapi.dll", EntryPoint = "SHAutoComplete", PreserveSig = false)] public static extern void SHAutoComplete( IntPtr hwndEdit, SHAutoCompleteFlags dwFlags );
内部でSetLastErrorで設定されたエラーコードをMarshal.GetLastWin32Error()で取得できるようにする
(GetLastError()のp/Invoke呼び出しではダメらしい)
[DllImport("user32.dll", SetLastError=true)] public static extern int MessageBox( IntPtr hWnd, String text, String caption, uint type );