場景:TaskCreate 建立執行緒,入口函數簽名為 void (*entryPoint)(void),但 pthread_create 要求 void *(*start_routine)(void *)。直接轉換呼叫有風險。
void *entry_wrapper(void (*entryPoint)(void)) {
entryPoint(); // 呼叫原始入口
return NULL;
}
int TaskCreate(..., void (*entryPoint)(void), ...) {
pthread_t thread;
pthread_attr_t attr;
// ... 屬性設定 ...
// 安全:傳遞 entryPoint 為參數給 wrapper
if (pthread_create(&thread, &attr, (void *(*)(void *))entry_wrapper, entryPoint) != 0)
return -1;
// ...
}
若 TaskCreate 需同時傳遞 entryPoint 與使用者參數 pPara,wrapper 只能接收單一 void *,無法同時綁定兩者。真正的高階函數應能「接收函數,回傳新函數指標(閉包)」,但 C 語言無法直接實現,需依賴外部庫(如 libffi)或手工組裝機器碼,複雜度極高。
function newCounter()
local i = 0
return function() -- 閉包
i = i + 1
return i
end
end
後續將探討 C 語言模擬閉包的進階技巧。