0%

创建第一个PHP扩展

下面使用的工具和源码都以PHP-5.3.13作为基础 > PHP-5.3.13开发环境编译

推荐的教程 https://github.com/walu/phpbook

编写第一个扩展

创建文件config.m4

1
2
3
4
5
6
7
8
9
10
PHP_ARG_ENABLE(
helloworld,
[Whether to enable the "helloworld" extension],
[enable-helloworld Enable "helloworld" extension support]
)

if test $PHP_HELLOWORLD != "no"; then
PHP_SUBST(HELLOWORLD_SHARED_LIBADD)
PHP_NEW_EXTENSION(helloworld, helloworld.c, $ext_shared)
fi

创建helloworld.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef HELLOWORLD_H
#define HELLOWORLD_H

//加载config.h,如果配置了的话
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

//加载php头文件
#include "php.h"
#define phpext_helloworld_ptr &helloworld_module_entry
extern zend_module_entry helloworld_module_entry;

#endif

创建helloworld.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "helloworld.h"

// 这边定义了hello_world
ZEND_FUNCTION(hello_world)
{
php_printf("Hello World!");
}

static zend_function_entry helloworld_functions[] = {
ZEND_FE(hello_world, NULL) // 第一个参数为函数名, 第二个参数为arg_info
// 可以继续添加
{NULL, NULL, NULL}
};

//module entry
zend_module_entry helloworld_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"helloworld", //这个地方是扩展名称,往往我们会在这个地方使用一个宏。
helloworld_functions, /* Functions */
NULL, /* MINIT */
NULL, /* MSHUTDOWN */
NULL, /* RINIT */
NULL, /* RSHUTDOWN */
NULL, /* MINFO */
#if ZEND_MODULE_API_NO >= 20010901
"1.0", //这个地方是我们扩展的版本
#endif
STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_HELLOWORLD
ZEND_GET_MODULE(helloworld)
#endif

编译扩展

phpize
./configure
make

然后就可以在 modules 目录下找到对应的 helloworld.so

加载扩展

php.ini 中加入

1
2
extension_dir=PATH/TO/EXTENSION
extension=helloworld.so

检查是否成功

1
php -r 'hello_world();'