hyadijxp 发表于 2018-12-14 12:46:50

PHP扩展开发之整型参数传递

实现一个加法函数,传入2个参数,计算相加的和:
1.创建一个新的扩展
./ext_skel --extname=hello
2.vi config.m4   去掉以下3行行首的dnl
          PHP_ARG_ENABLE(hello, whether to enable strive support,
          Make sure that the comment is aligned:
          [--enable-hello         Enable strive support])
3,编写代码
1.vi hello.c
2.#添加下面的代码
      ZEND_BEGIN_ARG_INFO(addition_arginfo, 0)
            ZEND_ARG_INFO(0, num1)
            ZEND_ARG_INFO(0, num2)
      ZEND_END_ARG_INFO()
PHP_FUNCTION(addition) {
      long num1,num2;
      if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &num1, &num2) == FAILURE) {
         return;
      }
      RETURN_LONG(num1+num2);
}
3.在数组中添加函数名:
const zend_function_entryhello_functions[] = {
          PHP_FE(addition, NULL)         /* addition function */
}

解释:
    这里创建的拓展名为hello,所以需要编辑hello.c文件,在里面加上相应的函数。这里加上了addition
    函数,主要功能是实现两个参数的相加。定义了2个参数,num1与num2。
    ZEND_BEGIN_ARG_INFO:开始参数块定义
    ZEND_END_ARG_INFO      :结束参数块定义
    ZEND_ARG_INFO      :声明普通参数
    PHP_FUNCTION(addition) :这里是为扩展添加具体的函数,函数名为(addition)
    函数内定义了两个long类型的变量,这里定义的变量与上面参数块中定义的对应。
    RETURN_LONG:表示返回一个long类型的值,
   
4.编译安装扩展,
       phpize
       ./configure --with-php-config=php_conf_dir
       make && make install
       vi php.ini
       extension=strive.so      
       reload php-fpm
5.测试addition函数是否可用:
             php -r 'echo addition(10,40);'
   
   
  




页: [1]
查看完整版本: PHP扩展开发之整型参数传递