萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

C# 調用 Windows API 核心要點總結

前言

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);
}

二、DllImport 關鍵屬性詳解

屬性作用常用值
CallingConvention調用約定(誰清理堆棧)StdCall (默認, WinAPI), Cdecl (C 標準, 可變參數)
CharSet字符串封送方式 + 函數名後綴Auto (NT=Unicode, 9x=Ansi), Ansi, Unicode
EntryPointDLL 中真實導出函數名/序號如 "MessageBoxW"
ExactSpelling禁止自動追加 A/W 後綴true 時需精確匹配
SetLastError調用 SetLastError 保存錯誤碼true 後可用 Marshal.GetLastWin32Error()
PreserveSig保留原始簽名不轉換 HRESULTCOM 互操作常用

三、參數類型映射表

Win32 類型C# 類型備註
DWORD, UINT, ULONGuint / UInt3232 位無符號
INT, LONG, BOOLint / Int3232 位有符號
HANDLE, HWND, HMODULEIntPtr平台相關指針大小
LPSTR, LPCSTRstring / StringBuilderANSI 字符串,StringBuilder 可修改
LPWSTR, LPCWSTRstringUnicode 字符串 (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 進階用法

[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 指定

六、垃圾回收陷阱與 HandleRef

若非托管代碼長期持有托管對象引用(如回調、異步操作),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 查找現成定義,避免重複造輪子與低級錯誤。

copyright © 萬盛學電腦網 all rights reserved