go语言编写php扩展,编写php扩展hello_world(),简单实现-Go语言中文社区

本文详细介绍了如何在PHP7.11中创建并编译一个名为hello的扩展。首先通过ext_skel脚本生成扩展骨架,然后修改config.m4文件去除注释并添加新函数hello_world。在hello.c文件中定义函数入口和主体,最后成功编译安装扩展并在php.ini中启用,使扩展在CLI和FPM模式下可用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先简单实现扩展编写

php7.1

1.下载一个源码包,进入ext目录,该目录下有个ext_skel脚本

2.执行命令 ./ext_skel --extname=hello ,命名扩展名

ext_skel自动生成扩展文件编写骨架

3.生成骨架之后需要进行一定的修改

config.m4 文件

# config.mg 文件中 dnl 是代码注释标识符

dnl PHP_ARG_ENABLE(hello, whether to enable hello support,

dnl Make sure that the comment is aligned:

dnl [ --enable-hello Enable hello support])

# 删除 第一行和第三行的dnl [去除注释]

hello.c 文件

//每添加一个函数都要在这里面声明zend函数入口

const zend_function_entry hello_functions[] = {

PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */

//这是新声明的函数

PHP_FE(hello_world, NULL)

PHP_FE_END /* Must be the last line in hello_functions[] */

};

//注册完之后编写函数主体

//直接把原来的confirm_hello_compiled函数主体copy过来了

PHP_FUNCTION(hello_world)

{

char *arg = NULL;

size_t arg_len, len;

zend_string *strg;

if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {

return;

}

strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "hello", arg);

RETURN_STR(strg);

}

#编译安装扩展

#我是能正常安装,所以一条执行

phpize && ./configure && make && make install

正常生成扩展之后,在php配置文件中加入新的扩展 extension=hello.so

cli模式下直接 php -r "echo hello_world('厉害啊')";

fpm需要重启php-fpm服务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值