public class Utility
{
// 完整屬性寫法
[DllImport("kernel32",
EntryPoint = "CreateDirectory",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Auto)]
public static extern bool CreateDirectory(string path);
// 簡寫:預設 StdCall、Ansi、EntryPoint 同方法名
[DllImport("user32", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, int type);
}
| 屬性 | 預設值 | 說明 |
|---|---|---|
CallingConvention | StdCall | Win32 API 幾乎皆為 StdCall;C 執行期函式 (cdecl) 需明確指定。 |
CharSet | Ansi | 控制字串封送與函數名修飾。建議 CharSet.Auto 或 Unicode。 |
EntryPoint | 方法名 | C# 方法名與 DLL 匯出名不同時必須指定。 |
SetLastError | false | true 時可用 Marshal.GetLastWin32Error() 取得錯誤碼。 |
原型:BOOL CreateDirectory(LPCTSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes);
// 呼叫
bool ok = CreateDirectory(@"C:\NewFolder", IntPtr.Zero);
LPCTSTR → string (配合 CharSet.Auto 自動轉 Unicode/ANSI)。LPSECURITY_ATTRIBUTES → IntPtr (傳 IntPtr.Zero 表示 NULL)。[StructLayout(LayoutKind.Sequential)] 並逐欄位對應。extern "C" __declspec(dllexport) 避免名稱修飾。__cdecl,需在 C# 指定 CallingConvention.Cdecl,或在 C++ 加 __stdcall。StringBuilder 並傳遞容量。SetLastError = true + Marshal.GetLastWin32Error() 取得 Win32 錯誤碼。