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