php扩展开发

本文介绍如何使用PHP自定义一个高效重复字符串的函数,通过扩展模块的方式避免频繁的内存重新分配,提高处理大量字符串时的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设你正在开发一个网站,需要一个把字符串重复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 

会出来如下提示

  1.  $ cd ..
  2. $ vi ext/myfunctions1/config.m4
  3.  $ ./buildconf
  4.   $ ./configure --[with|enable]-myfunctions1
  5.  $ make
  6. $ ./php -f ext/myfunctions1/myfunctions1.php
  7.  $ vi ext/myfunctions1/myfunctions1.c
  8.  $ make
Repeat steps 3-6 until you are satisfied with ext/myfunctions1/config.m4 and
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

代表扩展成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值