1.php安装,这个忽略了
2.编写C代码生成so文件,并且测试:
编写hello.c,生成对应so文件
#vim hello.c
int cc_add(int a, int b)
{
return a + b;
}
# gcc -O -c -fPIC -o hello.o hello.c // -fPIC:是指生成的动态库与位置无关
# gcc -shared -o libhello.so hello.o // -shared:是指明生成动态链接库
# cp libhello.so /usr/local/lib // 把生成的链接库放到指定的地址
# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf // 把库地址写入到配置文件中
# /sbin/ldconfig // 用此命令,使刚才写的配置文件生效
以下是测试so文件
编写hellotest.c文件进行测试so文件
#vi hellotest.c
#include <stdio.h>
int main()
{
int a = 4, b = 6;
printf("%d\n", cc_add(a,b));
return 0;
}
#gcc -o hellotest -lhello hellotest.c // 编译测试文件,生成测试程序
#./hellotest // 运行测试程序
3.制作php调用中间层模块:
(1)进入对应的php源码中,生成模块基础框架
#cd php-{你的版本号}/ext
#./ext_skel --extname=hello
#cd hello
(2)首先编辑 config.m4 文件,去掉注释(注释符号为 dnl 。)
# vim config.m4
PHP_ARG_ENABLE(hello, whether to enable hello support,
dnl Make sure that the comment is aligned:
[ --enable-hello Enable hello support])
(3)然后执行 phpize 程序,生成configure脚本:
#phpize
(4)打开 php_hello.h,在 PHP_FUNCTION(confirm_hello_compiled); /* For testing, remove later. */ 之下加入函数声明:
PHP_FUNCTION(hello_add);
(5)打开 hello.c,在 PHP_FE(confirm_hello_compiled, NULL) 附近内容修改如下
const zend_function_entry hello_functions[] = {
PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */
PHP_FE(hello_add, NULL) /* For testing, remove later. */
PHP_FE_END /* Must be the last line in hello_functions[] */
};
然后在 hello.c 的最末尾书写hello_add函数的内容:
PHP_FUNCTION(hello_add)
{
long int a, b;
long int result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) {
return;
}
result = cc_add(a, b);
RETURN_LONG(result);
}
(6)配置安装
#./configure --with-php-config=/usr/local/php/bin/php-config
修改Makefile中的 LDFLAGS=-lhello
#make
#make install
Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/
#cp modules/hello.so /usr/lib/php/modules
#cp modules/hello.so /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/
#vim /etc/php5/apache2/php.ini
enable_dl = Off; //允许dl()动态加载so扩展功能enable_dl = On
重启php,nginx或者apache。
然后建立一个简单站点,建立文件 hello.php
<html>
<body>
<?php
dl("hello.so");
echo hello_add(4, 6);
?>
</body>
</html>
然后在浏览器中打开hello.php文件,如果显示10,则说明函数调用成功了。
(7)这是动态加载类库,如果需要静态加载,可以直接修改php.ini文件:
enable_dl = Off
extension=hello.so
然后重启php
[注意,这种方式只适合hello.so库内所有功能代码已经全部调试ok,如果还处在调试期间,那么需要采用上面的dl强制加载的方式]
hello.php可以去掉dl动态加载语句:
<html>
<body>
<?php
echo hello_add(4, 6);
?>
</body>
</html>