PHP调用C函数简单例子

xiaoxiao2021-02-28  70

1、找到PHP扩展脚本ext_skel,ext_skel是PHP源代码中的脚本工具,位于目录ext下

find / -name ext_skel

2、 生成名字为helloworld的目录,该目录包含所需的文件

./ext_skel --extname=helloworld # cd helloworld/ # ls config.m4 config.w32 CREDITS EXPERIMENTAL helloworld.c helloworld.php php_helloworld.h tests

3、修改config.m4

//修改 dnl PHP_ARG_WITH(helloworld, for helloworld support, dnl Make sure that the comment is aligned: dnl [ --with-helloworld Include helloworld support]) //为 PHP_ARG_WITH(helloworld, for helloworld support, [ --with-helloworld Include helloworld support]) //dnl 代表注释,下边 –enable-myext,是表示编译到php内核中。with是作为动态链接库载入,with还对于需要另外库的函数

4、修改php_helloworld.h,(php7就不需要修改.h文件,直接在.c中添加函数)

//这里就是扩展函数声明部分 PHP_FUNCTION(confirm_myext_compiled); 下面增加一行 PHP_FUNCTION(myext_helloworld); //表示声明了一个myext_helloworld的扩展函数。

5、然后修改helloworld.c,这个是扩展函数的实现部分

//修改 const zend_function_entry myext_functions[] = { PHP_FE(confirm_myext_compiled, NULL) /* For testing, remove later. */ PHP_FE_END /* Must be the last line in myext_functions[] */ }; //这是函数主体,我们将我们的函数myext_helloworld的指针注册到PHP_FE,必须以PHP_FE_END 结束 const zend_function_entry myext_functions[] = { PHP_FE(confirm_myext_compiled, NULL) /* For testing, remove later. */ PHP_FE(myext_helloworld, NULL) PHP_FE_END /* Must be the last line in myext_functions[] */ }; //在helloworld.c末尾加myext_helloworld的执行代码。 PHP_FUNCTION(myext_helloworld) { char *arg = NULL; int arg_len, len; //这里说明该函数需要传递一个字符串参数为arg指针的地址,及字符串的长度 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } php_printf("Hello World!\n"); RETURN_TRUE; } //zend_parse_parameters的参数(类似scanf): ZEND_NUM_ARGS():传递给函数参数总个数的宏。 TSRMLS_CC:为了线程安全,宏。 "s":指定参数类型,s代表字符串。 &arg:传进来的参数存放在arg中 &arg_len:存放字符串长度 //返回值实现, RETURN_type()

6、参数传递和返回值 (1)zend_parse_parameters的参数(类似scanf):

ZEND_NUM_ARGS():传递给函数参数总个数的宏。 TSRMLS_CC:为了线程安全,宏。 "s":指定参数类型,s代表字符串。 &arg:传进来的参数存放在arg中 &arg_len:存放字符串长度

(2)返回值实现, RETURN_type()

7、在helloworld目录下依次执行phpize、./configure 、make、make install

//执行make install时,可以看到本地php的默认扩展读取目录 root@iZuf6fih:/code/php5-5.5.9+dfsg/ext/helloworld# make install Installing shared extensions: /usr/lib/php5/20121212/ //进入/usr/lib/php5/20121212/可以看到生成的 helloworld.so root@iZuf6fih# cd /usr/lib/php5/20121212/ root@iZuf6fih:/usr/lib/php5/20121212# ls beacon.so helloworld.so json.so lary.so mysqli.so mysql.so opcache.so pdo_mysql.so pdo.so readline.so

8、把编译出的.so文件加入php.ini中:

//php.ini一般位于/etc/php/7.0/apache2/php.ini下,在php.ini中搜索extension =,然后在下一行添加 extension = /usr/lib/php5/20121212/helloworld.so

9、重启apache

sudo /etc/init.d/apache2 restart

10、然后编写一个简单的php脚本来调用扩展函数:

<php echo myext_helloworld(); phpinfo();//输出的php信息中可以看到扩展库的产生 ?>
转载请注明原文地址: https://www.6miu.com/read-45711.html

最新回复(0)