PHP扩展开发
基础入门实例
-
生成扩展框架
cd ~/php-7.0.30/ext #进入源码包扩展目录
./ext_skel --extname=my_func #生成扩展基本架构 -
修改配置文件
-
打开配置文件 config.m4
dnl Otherwise use enable:
dnl PHP_ARG_ENABLE(my_func, whether to enable my_func support,
dnl Make sure that the comment is aligned:
dnl [ --enable-my_func Enable my_func support])
#修改为:
dnl Otherwise use enable:
PHP_ARG_ENABLE(my_func, whether to enable my_func support,
Make sure that the comment is aligned:
[ --enable-my_func Enable my_func support])dnl 是注释符,表示当前行是注释。这段话是说如果此扩展依赖其他扩展,去掉PHP_ARG_WITH段的注释符;否则去掉PHP_ARG_ENABLE段的注释符。显然我们不依赖其他扩展或lib库,所以去掉PHP_ARG_ENABLE段的注释符:
-
在 my_func.c 上实现函数功能
PHP_FUNCTION(my_func)
{
//zend_string *strg;
//strg = strpprintf(0, "hello world.");
//RETURN_STR(strg);
char *arg = NULL;
size_t arg_len;
char *strg;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
return;
}
strg = strpprintf(0, "Hello, my_func_print: %s", arg);
RETURN_STR(strg);
} -
添加到编译列表里(my_func.c):
const zend_function_entry my_func_functions[] = {
PHP_FE(my_func, NULL) /添加这行/
PHP_FE(confirm_my_func_compiled, NULL) /* For testing, remove later. /
PHP_FE_END / Must be the last line in my_func_functions[] */
}; -
编译与安装
/usr/local/php7/bin/phpize
./configure --with-php-config=/usr/local/php-7.0.31/bin/php-config
make && make install
#vim usr/local/php7/etc/php.ini
extension=my_func.so -
测试
php -r "echo my_func('this is a function extension.');"
不使用工具写扩展
-
一个扩展(如:world)至少包含3个文件:
- config.m4(phpize用来准备编译扩展的配置文件)
- php_world.h(引用包含的头文件)
- world.c(源码文件)
-
config.m4
PHP_ARG_ENABLE(world, whether to enable world support,
Make sure that the comment is aligned:
[ --enable-world Enable hello support])if test "$PHP_WORLD" != "no"; then
AC_DEFINE(HAVE_WORLD,1,[ ])
PHP_NEW_EXTENSION(world, world.c, $ext_shared,, -DZEND_ENABLE_STATIC_TSRMLS_CACHE=1)
fi -
php_world.h
ifndef PHP_WORLD_H
define PHP_WORLD_H
extern zend_module_entry hello_module_entry;
#define phpext_hello_ptr &hello_module_entry
#define PHP_WORLD_VERSION "0.1.0"
#define PHP_WORLD_EXTNAME "world"endif
-
world.c
ifdef HAVE_CONFIG_H
include "config.h"
endif
include "php.h"
include "php_world.h"
PHP_FUNCTION(world)
{
zend_string *strg;
strg = strpprintf(0, "hello world. (from world module)");
RETURN_STR(strg);
}const zend_function_entry world_functions[] = {
PHP_FE(world, NULL)
PHP_FE_END
};
zend_module_entry world_module_entry = {
STANDARD_MODULE_HEADER,
PHP_WORLD_EXTNAME,
world_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
PHP_WORLD_VERSION,
STANDARD_MODULE_PROPERTIES
};ifdef COMPILE_DL_WORLD
ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(world)
#endif -
编译安装:
同上
作者:T&D
Q Q:335749143
邮箱:tanda.arch#gmail.com(@替换#)
出处:http://www.cnblogs.com/one-villager/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号

