C# 通過 P/Invoke (Platform Invocation Services) 調用 Windows API,需引用 System.Runtime.InteropServices 命名空間。本文匯總聲明格式、參數映射、結構體封送、垃圾回收陷阱等核心要點。
using System.Runtime.InteropServices;
public class WinAPI {
// 基本聲明
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
// 指定 EntryPoint(方法名與 API 不同時)
[DllImport("user32.dll", EntryPoint = "MessageBoxW", CharSet = CharSet.Unicode)]
public static extern int MsgBox(IntPtr hWnd, string text, string caption, uint type);
}
| 屬性 | 作用 | 常用值 |
|---|---|---|
CallingConvention | 調用約定(誰清理堆棧) | StdCall (默認, WinAPI), Cdecl (C 標準, 可變參數) |
CharSet | 字符串封送方式 + 函數名後綴 | Auto (NT=Unicode, 9x=Ansi), Ansi, Unicode |
EntryPoint | DLL 中真實導出函數名/序號 | 如 "MessageBoxW" |
ExactSpelling | 禁止自動追加 A/W 後綴 | true 時需精確匹配 |
SetLastError | 調用 SetLastError 保存錯誤碼 | true 後可用 Marshal.GetLastWin32Error() |
PreserveSig | 保留原始簽名不轉換 HRESULT | COM 互操作常用 |
| Win32 類型 | C# 類型 | 備註 |
|---|---|---|
| DWORD, UINT, ULONG | uint / UInt32 | 32 位無符號 |
| INT, LONG, BOOL | int / Int32 | 32 位有符號 |
| HANDLE, HWND, HMODULE | IntPtr | 平台相關指針大小 |
| LPSTR, LPCSTR | string / StringBuilder | ANSI 字符串,StringBuilder 可修改 |
| LPWSTR, LPCWSTR | string | Unicode 字符串 (CharSet.Unicode) |
| 構造體 | struct / class + [StructLayout] | 需指定 LayoutKind.Sequential |
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct OSVERSIONINFO {
public uint dwOSVersionInfoSize;
public uint dwMajorVersion;
public uint dwMinorVersion;
public uint dwBuildNumber;
public uint dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool GetVersionEx(ref OSVERSIONINFO lpVersionInfo);
// 調用
var info = new OSVERSIONINFO { dwOSVersionInfoSize = (uint)Marshal.SizeOf() };
bool ok = GetVersionEx(ref info); // 必須用 ref
[MarshalAs(UnmanagedType.LPStr)] // ANSI 字符串指針
[MarshalAs(UnmanagedType.LPWStr)] // Unicode 字符串指針
[MarshalAs(UnmanagedType.Bool)] // 4 字節 BOOL
[MarshalAs(UnmanagedType.U1)] // 1 字節 BYTE
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] // 固定長度字符串數組
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] // 數組,長度由參數 1 指定
若非托管代碼長期持有托管對象引用(如回調、異步操作),GC 可能回收對象導致句柄失效。
// 錯誤示例:fileHandle 可能被 GC 回收
IntPtr fileHandle = CreateFile(...);
SomeAsyncApi(fileHandle); // 非托管異步使用
// 正確:HandleRef 綁定生命周期
var handleRef = new HandleRef(this, fileHandle);
SomeAsyncApi(handleRef);
// handleRef 確保 this 存活,從而 fileHandle 有效
Visual Studio 安裝目錄下包含大量現成定義:
C:\Program Files\Microsoft Visual Studio\\\SDK\Samples\Technologies\Interop\PlatformInvoke\WinAPIs\CS\
C# 調用 Windows API 核心在於:正確聲明簽名 (DllImport + 參數映射)、妥善處理字符串編碼、結構體佈局控制、生命周期管理。建議優先使用 pinvoke.net 查找現成定義,避免重複造輪子與低級錯誤。