假设你正在开发一个网站,需要一个把字符串重复n次的函数。下面是用PHP写的例子:
function self_concat($string, $n)
{
$result = "";
for ($i = 0; $i < $n; $i++) {
$result .= $string;
}
return $result;
}
self_concat("One", 3) returns "OneOneOne".
self_concat("One", 1) returns "One".
假设由于一些奇怪的原因,你需要时常调用这个函数,而且还要传给函数很长的字符串和大值n。这意味着在脚本里有相当巨大的字符串连接量和内存重新分配过程,以至显著地降低脚本执行速度。如果有一个函数能够更快地分配大量且足够的内存来存放结果字符串,然后把$string重复n次,就不需要在每次循环迭代中分配内存。
为扩展建立函数的第一步是写一个函数定义文件,该函数定义文件定义了扩展对外提供的函数原形。该例中,定义函数只有一行函数原形self_concat() :
string self_concat(string str, int n)
1../ext_skel --extname=myfunctions
会出来如下提示
- $ cd ..
- $ vi ext/myfunctions1/config.m4
- $ ./buildconf
- $ ./configure --[with|enable]-myfunctions1
- $ make
- $ ./php -f ext/myfunctions1/myfunctions1.php
- $ vi ext/myfunctions1/myfunctions1.c
- $ make
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
2.vim ext/myfunctions/config.m4
PHP_ARG_ENABLE(myfunctions, whether to enable myfunctions support,
[ --enable-myfunctions Include myfunctions support])
3.cd myfunctions
4.vi myfunctions.c
PHP_FUNCTION(confirm_myfunctions_compiled)
{
char *str = NULL;
int argc = ZEND_NUM_ARGS();
int str_len;
long n;
char *result; /* Points to resulting string */
char *ptr; /* Points at the next location we want to copy to */
int result_length; /* Length of resulting string */
if (zend_parse_parameters(argc TSRMLS_CC, "sl", &str, &str_len, &n) == FAILURE)
return;
/* Calculate length of result */
result_length = (str_len * n);
/* Allocate memory for result */
result = (char *) emalloc(result_length + 1);
/* Point at the beginning of the result */
ptr = result;
while (n--) {
/* Copy str to the result */
memcpy(ptr, str, str_len);
/* Increment ptr to point at the next position we want to write to */
ptr += str_len;
}
/* Null terminate the result. Always null-terminate your strings
even if they are binary strings */
*ptr = '/0';
/* Return result to the scripting engine without duplicating it*/
RETURN_STRINGL(result, result_length, 0);
}
5。/usr/local/webserver/php/bin/phpize
6../configure --with-php-config=/usr/local/webserver/php/bin/php-config
7.make && make install
8.加入扩展
编辑php.ini配置文件中加入: extension=myfunctions.so
测试结果
vim test.php
<?php
for ($i = 1; $i <= 3; $i++) {
print confirm_myfunctions_compiled("ThisIsUseless", $i);
print "\r\n";
}
print "\r\n";
exit;
输出:
ThisIsUseless
ThisIsUselessThisIsUseless
ThisIsUselessThisIsUselessThisIsUseless
代表扩展成功