1.用c为php写一个能够返回"Hello World"字符串的 c扩展
用php代码表示如下:
<?php
function hello_world() {
return 'Hello World';
}
?>
2.通过源码安装php(参考 php源码安装)
3.进入php源码目录下的ext目录,新建一个hello目录,进入hello目录,新建3个文件:
config.m4 phpize用来准备编译你的扩展的配置文件
php_hello.h 包含引用的头文件
hello.c 包含 hello_world 函数的源码文件
4.config.m4中填写内容:
PHP_ARG_ENABLE(hello, whether to enable Hello
World support,
[ --enable-hello Enable Hello World support])
if test "$PHP_HELLO" = "yes"; then
AC_DEFINE(HAVE_HELLO, 1, [Whether you have Hello World])
PHP_NEW_EXTENSION(hello, hello.c, $ext_shared)
fi
5.php_hello.h中填写的内容:
#ifndef PHP_HELLO_H
#define PHP_HELLO_H 1
#define PHP_HELLO_WORLD_VERSION "1.0"
#define PHP_HELLO_WORLD_EXTNAME "hello"
PHP_FUNCTION(hello_world);
extern zend_module_entry hello_module_entry;
#define phpext_hello_ptr &hello_module_entry
#endif
6.hello.c中填写的内容:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_hello.h"
static zend_function_entry hello_functions[] = {
PHP_FE(hello_world, NULL)
{NULL, NULL, NULL}
};
zend_module_entry hello_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
PHP_HELLO_WORLD_EXTNAME,
hello_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
#if ZEND_MODULE_API_NO >= 20010901
PHP_HELLO_WORLD_VERSION,
#endif
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_HELLO
ZEND_GET_MODULE(hello)
#endif
PHP_FUNCTION(hello_world)
{
RETURN_STRING("Hello World", 1);
}
7.执行如下命令:
$ phpize
$ ./configure --enable-hello
$ make
8.编译完成后在modules目录下会生成hello.so,将其拷贝到 php的extension_dir下,修改php.ini添加 extension=hello.so,重启服务器(如果是nginx,还需要重启php-fpm服务)。
9.测试hello扩展
<?php
echo hello_world();
输出 Hello World 成功!