萬盛學電腦網

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

PHP 調用 C 代碼三大路徑:system()、Daemon、PHP 擴展開發完整指南

三種調用模式對比

方式適用場景效能複雜度缺點
system()/exec()現成 CLI 工具、低頻任務、隔離崩潰風險低(進程啟動開銷大)低頻繁調用效能差、參數傳遞麻煩、難共享記憶體
Daemon + Socket長運行 C 服務、高頻調用、需共享狀態高(常駐進程)中高需自行實現協議、進程管理、容錯
PHP Extension (C)計算密集型、高頻調用、需無縫整合 PHP 變量極高(原生速度,僅參數轉換開銷)高需 C 基礎、編譯部署、版本綁定、段錯誤風險

重點:開發 PHP 擴展(不重新編譯 PHP)

1. 準備骨架

# 在 PHP 原始碼 ext/ 目錄下
./ext_skel --extname=hello
# 生成 hello/ 目錄,關鍵文件:
# config.m4  - 編譯配置
# hello.c    - 核心實現
# php_hello.h - 函數聲明

2. 修改 config.m4 啟用 --with-hello

# 找到並取消註釋:
PHP_ARG_WITH(hello, for hello support,
[  --with-hello             Include hello support])

3. 編譯安裝

cd hello
phpize
./configure --with-hello
make
# 生成 modules/hello.so

4. 動態載入(無需修改 php.ini)

<?php
function dl_local($soFile) {
    if (!ini_get('enable_dl') || ini_get('safe_mode')) die('dl() 禁用');
    $path = __DIR__ . '/' . $soFile;
    if (!is_executable($path)) die("$soFile 不可執行");
    // 計算相對 extension_dir 的路徑
    $extDir = ini_get('extension_dir');
    $depth = substr_count($extDir, '/');
    $rel = str_repeat('../', $depth) . $path;
    if (!dl($rel)) die('載入失敗');
    return true;
}

if (!extension_loaded('hello')) dl_local('hello.so');

// 調用擴展函數
echo hello_world(); // 假設實現了 hello_world()
?>

5. 實現函數:參數解析與返回值

// hello.c
#include "php_hello.h"

ZEND_FUNCTION(hello_strdiff) {
    char *s1 = NULL, *s2 = NULL;
    size_t len1, len2;

    // 參數解析:"ss" 兩個字串
    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &s1, &len1, &s2, &len2) == FAILURE) {
        return;
    }

    // 計算編輯距離(Levenshtein 簡化版)
    // ... 算法邏輯 ...
    long distance = calculate_distance(s1, len1, s2, len2);

    RETURN_LONG(distance); // 返回長整數
}

// 函數表註冊
const zend_function_entry hello_functions[] = {
    ZEND_FE(hello_strdiff, NULL)
    ZEND_FE_END
};

參數類型對照表

效能實測參考

  • 純 PHP 算法基準:1x
  • PHP 擴展:~90x 加速(參數轉換為主要開銷)
  • 純 C 程式:~500x 加速

現代替代:FFI (PHP 7.4+)

<?php
$ffi = FFI::cdef(
    "int add(int a, int b);",
    "libmath.so" // 或 .dll/.dylib
);
echo $ffi->add(2, 3); // 5
?>

FFI 允許純 PHP 調用共享庫函數,無需編寫 C 擴展,適合中等效能需求、快速原型。

copyright © 萬盛學電腦網 all rights reserved
類型字母C 類型說明
lzend_long整數
ddouble浮點數
schar*, size_t字串(需傳長度變量)
bzend_bool布爾值
azval*陣列
ozval*物件
rzval*資源
zzval*任意類型(zval*)