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

C 語言函數指針數組詳解:從 Linux 內核 socket_ops 到實戰封裝

     編輯:關於C語言

背景:內核中的函數指針結構體

Linux 內核 struct proto_ops 大量使用函數指針作為成員,實現面向對象的多態:

struct proto_ops {
    int family;
    int (*release)(struct socket *sock);
    int (*bind)(struct socket *sock, struct sockaddr *addr, int len);
    int (*connect)(struct socket *sock, struct sockaddr *addr, int len, int flags);
    // ... 更多操作
};

這是 C 語言模擬「介面/虛函數」的核心模式:數據結構 + 函數指針 = 多態。

聲明語法解析

int (*release)(struct socket *sock);
// 讀法:release 是指針,指向「參數為 socket*,返回 int」的函數

函數指針數組實戰

#include <stdio.h>
#include <stdlib.h>

int func1(int n) { printf("func1: %d\n", n); return n; }
int func2(int n) { printf("func2: %d\n", n); return n; }

int main() {
    // 數組元素類型:int (*)(int)
    int (*fp[2])(int) = { func1, func2 };

    fp[0](1);  // 輸出 func1: 1
    fp[1](2);  // 輸出 func2: 2
    return 0;
}

關鍵語法點

  • int (*fp[2])(int):fp 是數組,元素是函數指針
  • 賦值時函數名自動轉換為地址
  • 調用語法 fp[i](arg) 與普通函數一致

C vs C++ 結構體差異

應用場景

  • 回調函數表(事件循環、驅動程序操作集)
  • 狀態機跳轉表
  • 插件架構、動態分發
  • 嵌入式系統固件跳轉向量表

總結

函數指針數組是 C 語言實現「策略模式」「命令模式」的基石。內核 file_operations、proto_ops 皆為經典範例。掌握其聲明、賦值、調用三步驟,即可靈活構建可擴展的 C 系統。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
特性C 結構體C++ 結構體/類
成員函數不允許允許
封裝無public/private/protected
繼承/多態手動模擬原生支持
默認訪問publicstruct:public, class:private