首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 呼叫 API (2):進階技巧——結構體與 GetSystemInfo 實戰

     編輯:關於C語言

C# 操作 API 進階:使用結構體

操作帶結構體的 API 比簡單 API 複雜,但掌握流程後,整個 API 世界將在掌握中。以下以 GetSystemInfo API 取得系統完整資訊為例。

步驟 1:建立專案與匯入命名空間

建立 C# Form 專案,加入 Button,代碼視窗匯入:

using System.Runtime.InteropServices;

步驟 2:宣告對應結構體

使用 StructLayout(LayoutKind.Sequential) 確保記憶體配置順序與 Win32 結構一致:

[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
    public uint dwOemId;
    public uint dwPageSize;
    public uint lpMinimumApplicationAddress;
    public uint lpMaximumApplicationAddress;
    public uint dwActiveProcessorMask;
    public uint dwNumberOfProcessors;
    public uint dwProcessorType;
    public uint dwAllocationGranularity;
    public uint dwProcessorLevel;
    public uint dwProcessorRevision;
}

步驟 3:宣告 API 函式

[DllImport("kernel32")]
static extern void GetSystemInfo(ref SYSTEM_INFO pSI);

步驟 4:按鈕點擊事件中呼叫

protected void button1_Click(object sender, System.EventArgs e)
{
    try
    {
        SYSTEM_INFO pSI = new SYSTEM_INFO();
        GetSystemInfo(ref pSI);
        // 接收回傳結構體後,即可操作其欄位
        // e.g. listBox1.InsertItem(0, pSI.dwActiveProcessorMask.ToString());
    }
    catch (Exception er)
    {
        MessageBox.Show(er.Message);
    }
}

關鍵要點總結

  • StructLayout 屬性控制記憶體配置,Sequential 依宣告順序排列。
  • 結構體欄位型別必須與 Win32 API 定義對應(uint 對應 DWORD 等)。
  • ref 關鍵字傳遞結構體參考,對應 API 的指標參數。
  • DllImport 指定 DLL 名稱(kernel32 會自動尋找 kernel32.dll)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved