用C语言编写PHP扩展

1:预定义

vi myfunctions.def

string self_concat(string str, int n)

2:到PHP源码目录的ext目录

#cd /usr/local/php-5.4.0/ext/

执行命令,生成对应扩展目录

#./ext_skel --extname=caleng_module --proto=/home/hm/caleng_module.def

./ext_skel --extname=myfunctions --proto=myfunctions.def

3:修改config.m4

vi config.m4

去掉dnl的注释

PHP_ARG_ENABLE(caleng_module, whether to enable caleng_module support,

Make sure that the comment is aligned:

[  --enable-caleng_module          Enable caleng_module support])

php源码根目录

./buildconf

修改vi myfunctions.c

PHP_FUNCTION(self_concat)

{

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);

}

执行

/usr/local/php/bin/phpize

./configure --with-php-config=/usr/local/php/bin/php-config

make

make install

修改

vi php.ini

php.ini增加扩展信息

extension=myfunctions.so

重启Nginx和php-fpm。

检查有没有加载都这个模块了

/usr/local/php/bin/php -m 或者 phpinfo()

把PHP加入到环境变量  export PATH=$PATH:/usr/local/webserver/php/bin

执行

php -r "echo self_concat('One', 3);"



参考:

http://www.cnblogs.com/benio/archive/2010/09/25/1834655.html

http://www.laruence.com/2008/08/16/301.html

http://blog.csdn.net/sanbingyutuoniao123/article/details/51921510

你可能感兴趣的:(用C语言编写PHP扩展)