2024-09-22

C 扩展如何访问 PHP 变量和函数?

c 扩展可以通过 zend api 访问 php 变量和函数,具体步骤如下:使用 zend_hash_find 查找指定哈希表中的 php 变量。使用 zend_hash_find_ptr 查找指定哈希表中的 php 函数。使用 zend_fcall_info 和 zend_call_function 调用 php 函数。

C 扩展如何访问 PHP 变量和函数?

C 扩展访问 PHP 变量和函数

PHP 通过 Zend API 为 C 扩展提供了访问其变量和函数的能力。这使开发人员能够创建与 PHP 紧密集成的自定义扩展。

访问 PHP 变量

立即学习PHP免费学习笔记(深入)”;

要访问 PHP 变量,可以使用以下函数:

zval *zend_hash_find(HashTable *htbl, const char *key, int key_len);
登录后复制

该函数在指定的哈希表中查找指定键名的变量。如果找到变量,则返回指向其 zval 结构的指针,其中包含变量的值和类型信息。

访问 PHP 函数

要调用 PHP 函数,可以使用以下函数:

zend_function *zend_hash_find_ptr(HashTable *htbl, const char *key, int key_len);
登录后复制

该函数在指定的哈希表中查找指定名称的函数。如果找到函数,则返回指向其 zend_function 结构的指针,其中包含函数的实现。要调用函数,可以使用以下语句:

zend_fcall_info fci;
zend_fcall_info_init(&fci, NULL, NULL, NULL, &retval, NULL);
zend_call_function(&fci, NULL);
登录后复制

实战案例

为了演示如何使用 Zend API,我们创建一个简单的 C 扩展,该扩展将向 PHP 添加一个名为 my_greet 的函数:

#include "zend_api.h"

static zend_function_entry my_functions[] = {
    {"my_greet", ZEND_FN(my_greet), ZEND_FN_STATIC | ZEND_FN_RETURNS_VALUE, ZEND_NUM_ARGS(1)},
    {NULL, NULL, NULL}
};

ZEND_DECLARE_MODULE_GLOBALS(my_extension)

static PHP_MINIT_FUNCTION(my_extension)
{
    zend_register_module_globals_ex(&my_extension_globals, sizeof(my_extension_globals));
    zend_register_functions(my_functions, sizeof(my_functions), NULL);
    return SUCCESS;
}

static PHP_RINIT_FUNCTION(my_extension)
{
    return SUCCESS;
}

static PHP_RSHUTDOWN_FUNCTION(my_extension)
{
    zend_unregister_functions(my_functions, sizeof(my_functions));
    zend_unregister_module_globals(my_extension_globals);
    return SUCCESS;
}

static PHP_FUNCTION(my_greet)
{
    char *name;
    size_t name_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, &name_len) == FAILURE) {
        return;
    }

    php_printf("Hello, %s!/n", name);
}

zend_module_entry my_extension_module = {
    STANDARD_MODULE_HEADER,
    "my_extension",
    my_functions,
    PHP_MINIT(my_extension),
    PHP_RINIT(my_extension),
    PHP_RSHUTDOWN(my_extension),
    NULL,
    NULL,
    NULL
};
登录后复制

编译并安装此扩展后,您可以在 PHP 代码中使用 my_greet 函数,如下所示:

my_greet("John");
登录后复制

以上就是C 扩展如何访问 PHP 变量和函数?的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1011549.html

发表回复

Your email address will not be published. Required fields are marked *