欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP扩展开发-LINUX环境的代码实例分享

程序员文章站 2022-05-22 20:23:48
...


LINUX环境下开发PHP扩展的步骤如下:

1、下载PHP源码,解压,我的解压目录是:/root/lamp/php-5.5.37

2、cd到/root/lamp/php-5.5.37/ext目录下,创建文件test_extension.def文件

int a(int x, int y)string b(string str, int n)

3、通过扩展框架生成器生成框架目录:
ext_skel –extname=test_extension –proto=test_extension.def
生成成功结果如下:

Creating directory test_extension
awk: /root/lamp/php-5.5.37/ext/skeleton/create_stubs:56: warning: escape sequence `\|' treated as plain `|'
Creating basic files: config.m4 config.w32 .svnignore test_extension.c php_test_extension.h CREDITS EXPERIMENTAL tests/001.phpt test_extension.
php [done].To use your new extension, you will have to execute the following steps:
1.  $ cd ..
2.  $ vi ext/test_extension/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-test_extension
5.  $ make
6.  $ ./sapi/cli/php -f ext/test_extension/test_extension.php
7.  $ vi ext/test_extension/test_extension.c
8.  $ make
Repeat steps 3-6 until you are satisfied with ext/test_extension/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.

4、切换到生成的框架目录下:cd test_extension
5、修改配置文件config.m4,去掉10、11、12行前面的dnl,如下

PHP_ARG_WITH(test_extension, for test_extension support,
Make sure that the comment is aligned:
[  --with-test_extension             Include test_extension support])

6、实现函数a和b的功能,vi test_extension.c,修改后函数a、b如下

PHP_FUNCTION(a)
{        
int argc = ZEND_NUM_ARGS();        
long x;        
long y;        
if (zend_parse_parameters(argc TSRMLS_CC, "ll", &x, &y) == FAILURE)
        {
                php_error(E_WARNING, "zend_parse_parameters failure!");                
                return;
        }
        RETURN_LONG(x + y);
}

PHP_FUNCTION(b)
{        
char *str = NULL;        
int argc = ZEND_NUM_ARGS();        
int str_len;        
long n;        
char *result;        
char *ptr;        
int result_length;        
if (zend_parse_parameters(argc TSRMLS_CC, "sl", &str, &str_len, &n) == FAILURE)
        {
        
                php_error(E_WARNING, "zend_parse_parameters failure!");                
                return;
        }
        result_length = str_len * n;
        result = (char *) emalloc(result_length + 1);
        ptr = result;        while (n--) {
                memcpy(ptr, str, str_len);
                ptr += str_len;
        }
        *ptr = '/0';
        RETURN_STRINGL(result, result_length, 0);

}

7、test_extension目录下执行:/usr/local/bin/phpize

Configuring for:
PHP Api Version:         
20121113Zend Module Api No:      
20121212Zend Extension Api No:   
220121212

8、配置:./configure –with-php-config=/usr/local/bin/php-config
9、编译:make
10、安装:make install
安装完成后/usr/local/lib/php/extensions/no-debug-zts-20121212/下会生成test_extension.so

11、修改php.in,加上:extension=test_extension.so

以上就是PHP扩展开发-LINUX环境的代码实例分享的详细内容,更多请关注其它相关文章!