注释:我来自于一个与/ PHP相关的背景,对C语言没有太多经验。
我目前正在编写一个PHP扩展,它需要检查是否加载了另一个模块,为此,我在整个扩展过程中复制和粘贴了以下代码片段:
#include "php.h"
const char* name = "hash";
if (zend_hash_str_exists(&module_registry, name, sizeof(name) - 1)) {
return; // Doesn't end up here, module is loaded
}
// Returns true and thus ends up here我决定将它放入自己的方法中,以使我的代码更加清晰,但是每当我这样做时,该方法似乎返回FALSE或NULL。这是我使用的方法:
#include "php.h"
zend_bool extension_module_exists(const char* name)
{
return zend_hash_str_exists(&module_registry, name, sizeof(name) - 1);
}
const char* name = "hash";
if (extension_module_exists(name) == false) {
return; // Now I end up here
}有人能告诉我我可能做错了什么吗?谢谢。
发布于 2017-06-07 08:42:11
我认为你的第一个版本也不起作用,如这里所示。你有机会
const char name[] = "hash";而不是
const char* name = "hash";代码是错误的,因为sizeof()所做的事情与您想象中的不同。它返回其参数的实际存储大小,如果此参数是指针,则返回的大小是指针的大小,而不是它所指向的对象的大小。
对于字符串的长度,在string.h中有一个函数string.h,您应该使用它而不是sizeof()。
示例:
zend_bool extension_module_exists(const char* name)
{
return zend_hash_str_exists(&module_registry, name, strlen(name));
}注意,这有一些开销,因为strlen()必须扫描其参数以找到第一个0-byte,它在C中标记字符串的结尾。
尽管如此,您可能应该考虑重新构造模块,只检查另一个扩展,并将结果保存在变量中。
https://stackoverflow.com/questions/44407439
复制相似问题