PHP的SO扩展编程入门


获取PHP源代码
http://www.php.net/downloads.php#v5

解压缩源代码包

$ cd php-5.2.5/ext
建立扩展函数原型文件,下面会用到
gedit tsing.proto
输入函数原型
string say_hello(string str_name)
保存并退出gedit

生成扩展
$ ./ext_skel --extname=tsing --proto=tsing.proto
ext_sket 顾名思义是生成扩展模块的基本骨架,tsing 为扩展模块名称,执行后将在ext目录下建立相应名称的目录

$ cd tsing

修改文件config.m4
#gedit ./ext/my_so_name/config.m4
去掉以下几行代码注释标记"dnl"
PHP_ARG_WITH(tsing, for tsing support,
Make sure that the comment is aligned:
[ --with-tsing Include tsing support])
或如下几行的注释标记
PHP_ARG_ENABLE(tsing, whether to enable test support,
Make sure that the comment is aligned:
[ --enable-tsing Enable test support])
这几行是说明PHP编译时加载SO模块的方式 with-tsing 或是 enable-tsing
with-tsing 表示需要第三方库,enable-tsing 表示不需要第三方库。

#gedit ./ext/tsing/tsing.c
在第43行看到say_hello函数自动在头部已经注册
/* {{{ tsing_functions[]
*
* Every user visible function must have an entry in tsing_functions[].
*/
zend_function_entry tsing_functions[] = {
PHP_FE(confirm_tsing_compiled, NULL) /* For testing, remove later. */
PHP_FE(say_hello, NULL)
{NULL, NULL, NULL} /* Must be the last line in tsing_functions[] */
};
/* }}} */
在第177行可以看到在原型文件tsing.proto中定义的函数已经在tsing.c中生成了代码skel
/* {{{ proto string say_hello(string str_name)
*/
PHP_FUNCTION(say_hello)
{
char *str_name = NULL;
int argc = ZEND_NUM_ARGS();
int str_name_len;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &str_name, &str_name_len) == FAILURE)
return;
php_error(E_WARNING, "say_hello: not yet implemented");
}
/* }}} */
如下注释掉第186行代码
// php_error(E_WARNING, "say_hello: not yet implemented");
添加
php_printf("Hello,".str_name.";");
保存并退出gedit

查看头文件
#gedit ./ext/tsing/php_tsing.h
发现在44行已经添加好了say_hello函数的原型
PHP_FUNCTION(say_hello);
保存并退出gedit

配置
有两种方式进行配置
方法A
#./buildconf --force (加上force参数是避免您使用的php版本为release版本)
#./configure --disable-all --with-tsing=shared --with-apxs2=/usr/sbin/apxs --prefix=/usr/lib/php/modules
上面命令中,--disable-all是为了加快编译速度而使用的,减少php默认要编译的模块数量。 --with-tsing=shared为了编译后能直接生产.so文件, --with-apxs2=/usr/sbin/apxs是根据您服务器上apache安装具体路径和版本来确定的

方法B
找到php安装目录里的 bin/phpize
$ /usr/bin/phpize
在 tsing 目录下生成configure文件
确定php-config文件和apxs安装位置,运行configure
./configure --with-php-config=/usr/bin/php-config --enable-tsing=shared --with-apxs2=/usr/sbin/apxs --prefix=/usr/lib/php/modules

编译
#make

安装
#gedit /etc/php.d/tsing.ini 加入extension=tsing.so

#make install 或 #cp ./ext/tsing/.libs/tsing.so /usr/lib/php/ext/

重启APACHE

查看phpinfo()函数结果,确认存在tsing一栏

如此在调用文件中可以直接使用动态扩展的函数
echo say_hello("Tsing");
输出
Hello,Tsing;

相关内容