用C语言写php扩展

xiaoxiao2021-02-28  94

php底层扩展的编写步骤如下所示: 1:预定义 在home目录,也可以其他任意目录,写一个文件,例如caleng_module.def 内容是你希望定义的函数名以及参数: int a(int x,int y) string b(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   在UNIX下一个叫ext_skel的脚本被用于建立扩展的骨 架,骨架信息从一个描述扩展接口的定义文件中取得。   3. 修改config.m4,去掉dnl的注释 4. 修改caleng_module.c PHP_FUNCTION(a) {  int argc = ZEND_NUM_ARGS();  int x;  int y;     int z;  if (zend_parse_parameters(argc TSRMLS_CC, "ll", &x, &y) == FAILURE)    return; z=x+y;   RETURN_LONG(z); } 函数自身的定义 使用了宏PHP_FUNCTION(),该宏可以生成一个适合于Zend引擎的函数原型。 ZEND_NUM_ARGS()  用户实际传递参数的数量 zend_parse_parameters 获取函数调用者传递过来的参数 RETURN_LONG Returns a long.   第二个函数 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);   } 上面的功能,实现的是下面的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".   5. 生成扩展库 #cd ./caleng_module #/usr/local/php/bin/phpize #./configure --with-php-config=/usr/local/php/bin/php-config #make #make install   6. 到php的对应extensions目录 #cd /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/ 改目录下有生成的caleng_module.so文件   7. 修改php.ini extension=caleng_module.so     8. 重启nginx 9. 检查加载 /usr/local/php/bin/php -m 10. PHP调用 echo a(1,2);
转载请注明原文地址: https://www.6miu.com/read-17714.html

最新回复(0)