Mac下開發PHP的C擴展
- 2020 年 2 月 20 日
- 筆記
1.下載php原文件
2.進入下載的php原文件
進入ext文件夾
cd ext
生成文件
sudo ./ext_skel.php --ext test
進入生成的test文件夾
cd test
設置許可權
sudo chmod 777 config.m4 php_test.h test.c
3.在test文件夾中進行操作
(1).php_test.h 文件中聲明函數
PHP_FUNCTION(test_add);
(2).修改config.m4文件,修改後要調用 phpize ./configure
刪除dnl放開注釋 __WITH 是引用的外部庫文件又引用了其他鏈接庫。 如果是引用單一的一個so文件,放開 __ENABLE注釋
dnl PHP_ARG_WITH([test], dnl [for test support], dnl [AS_HELP_STRING([--with-test], dnl [Include test support])])
PHP_ARG_ENABLE([hello], [whether to enable hello support], [AS_HELP_STRING([--enable-hello], [Enable hello support])], [no])
(3).修改 test.c文件 (主函數文件)
- 函數聲明
static const zend_function_entry test_functions[] = { PHP_FE(test_test1, arginfo_test_test1) PHP_FE(test_test2, arginfo_test_test2) PHP_FE(test_add,NULL) //添加函數聲明 PHP_FE_END };
- 函數實現
PHP_FUNCTION(test_add) { long a; long b; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a,&b) == FAILURE) { return; } long result = a+b; RETURN_LONG(result); }
4.終端執行
phpize
./configure sudo make make test sudo make install

終端執行如下,查看到php.ini地址
php -i | grep php.ini

打開php.ini文件
vim /usr/local/etc/php/7.2/php.ini
extension_dir = 執行sudo make install命令之後的地址
extension=php擴展名稱.so
extension_dir = /usr/local/Cellar/[email protected]/7.2.16/bin/20170718/ extension=test.so
重啟,在終端執行命令:
sudo /usr/sbin/apachectl restart
檢測擴展是否可用,在終端執行命令:
php -r 'echo tes_tadd(1,2);'
參考文章
https://www.jianshu.com/p/3a542418d968
https://www.cnblogs.com/bugchao/p/9051859.html
https://segmentfault.com/a/1190000007575322