用C语言写了一个库,在OC上能直接调用,在Android上打包成.so文件后也可以直接用,在PHP上想用,就要做成一个C扩展,这样一份算法就可以开开心心地在iOS、Android、H5上使用了
进入ext文件夹
cd ext
生成文件
sudo ./ext_skel.php --ext test
进入生成的test文件夹
cd test
设置权限
sudo chmod 777 config.m4 php_test.h test.c
PHP_FUNCTION(test_add);
删除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])
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);
}
phpize
./configure
sudo make
make test
sudo make install
如果./configure报如下错误,安装GCC软件套件
configure: error: no acceptable C compiler found in $PATH
yum install gcc
php -i | grep php.ini
vim /usr/local/etc/php/7.2/php.ini
extension_dir = 执行sudo make install命令之后的地址
extension=php扩展名称.so
extension_dir = /usr/local/Cellar/php@7.2/7.2.16/bin/20170718/
extension=test.so
sudo /usr/sbin/apachectl restart
php -r 'echo tes_tadd(1,2);'
phpize
Can't find PHP headers in /usr/include/php
The php-devel package is required for use of this command.
which phpize
/usr/bin/phpize
/usr/bin/phpize
Can't find PHP headers in /usr/include/php
The php-devel package is required for use of this command.
没安装 php-devel 这个扩展包。phpize是用来扩展php扩展模块的,通过phpize可以建立php的外挂模块,phpize 是属于php-devel的内容,
php -v
PHP 7.0.32 (cli) (built: Sep 15 2018 07:54:46) ( NTS )
Copyright (c) 1997-2017 The PHP Group
yum install php70w-devel
./configure报错,错误主要是没有C编译器.
configure: error: no acceptable C compiler found in $PATH
安装C编译器:
yum -y install gcc
./configure成功
sudo make报错,是因为在gcc中直接在for循环中初始化了增量,这语法在gcc中是错误的,必须先先定义i变量:
'for' loop initial declarations are only allowed in C99 mode
for(int i = (int) strlen(string); i >= len; i--){
把int 放到外边
sudo make install
Installing shared extensions: /usr/lib64/php/modules/
打开php.ini,末尾添加
extension_dir = /usr/lib64/php/modules/
extension=test.so
如果出现在命令行打印可以输出,但是在laravel里调用不到函数,我的做法是重启服务器,重新从phpize走一遍,还有ext的权限
参考文章
https://www.jianshu.com/p/3a542418d968
https://www.cnblogs.com/bugchao/p/9051859.html
https://segmentfault.com/a/1190000007575322
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。