PHP 扩展是对 PHP 功能的一个补充,编写完 PHP 扩展以后, ZEND 引擎需要获取到 PHP 扩展的信息,比如 phpinfo() 函数是如何列出 PHP 扩展的信息,PHP 扩展中的函数如何提供给 PHP 程序员使用,这些是开发 PHP 扩展需要了解的内容。
这些内容并不复杂,在开发 PHP 扩展时只要愿意去了解一下相关的部分就可以了,在这里,我给出一个简单的介绍。
PHP 扩展中负责提供信息的结构体为 zend_module_entry,该结构体的定义如下:
1 struct_zend_module_entry {2 unsigned shortsize;3 unsigned intzend_api;4 unsigned charzend_debug;5 unsigned charzts;6 const struct _zend_ini_entry *ini_entry;7 const struct _zend_module_dep *deps;8 const char *name;9 const struct _zend_function_entry *functions;10 int (*module_startup_func)(INIT_FUNC_ARGS);11 int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);12 int (*request_startup_func)(INIT_FUNC_ARGS);13 int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);14 void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);15 const char *version;16 size_t globals_size;17 #ifdef ZTS18 ts_rsrc_id*globals_id_ptr;19 #else
20 void*globals_ptr;21 #endif
22 void (*globals_ctor)(void *global);23 void (*globals_dtor)(void *global);24 int (*post_deactivate_func)(void);25 intmodule_started;26 unsigned chartype;27 void *handle;28 intmodule_number;29 const char *build_id;30 };
有了上面的结构体以后,那么 PHP 扩展的信息就已经有了,那么就可以将该结构体的信息提供给 ZEND 引擎,获取该结构体信息的函数为 get_module(),该函数的定义如下:
1 #define ZEND_GET_MODULE(name) \
2 BEGIN_EXTERN_C()\3 ZEND_DLEXPORT zend_module_entry *get_module(void) { return &name##_module_entry; }\4 END_EXTERN_C()
get_module() 函数返回一个 zend_module_entry 结构体的指针,通过 ## 完成字符串的拼接,然后通过 & 取地址符获得结构体的内容即可。
通过这两部分就可以完成 PHP 扩展到 ZEND 引擎的整合,不过好在 zend_module_entry 结构体会由扩展模板生成工具进行填充,而 get_module() 函数也不需要我们自己去调用,但是整合的原理还是要大体了解一下的,具体信息可以阅读相关的源码去进行理解。
欢迎大家关注微信公众号:“码农UP2U”