如何在PHP扩展中实例化全局C++类
How to instantiate a global C++ class within a PHP extension?
我正在将一个C++类实例化为PHP扩展中的全局类。然而,它是有效的,valgrind报告了一个明确的内存泄漏。
在我的php_myext.h中,我声明全局使用:
ZEND_BEGIN_MODULE_GLOBALS(myext)
MyClass *myClass;
ZEND_END_MODULE_GLOBALS(myext)
在我的PHP_MINIT_FUNCTION中,我为全局设置了初始化器和析构函数:
ZEND_INIT_MODULE_GLOBALS(myext, myext_init_globals, myext_destroy_globals);
然后我的初始化器和析构函数实现如下:
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
static void myext_init_globals(zend_myext_globals *myext_globals)
{
myext_globals->myClass = new MyClass();
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
static void myext_destroy_globals(zend_myext_globals *myext_globals)
{
delete myext_globals->myClass;
}
我已经使用以下内容向PHP公开了MyClass::test()方法:
static PHP_METHOD(MyExt, test)
{
RETURN_STRING(MYEXT_G(myClass)->test().c_str(), 1);
}
从我的PHP脚本来看一切都很好:
<?php echo MyExt::test(); ?>
然而,当我放弃我的测试脚本(test.php)时,我得到了一个泄漏:
LEAK SUMMARY:
definitely lost: 8 bytes in 1 blocks
indirectly lost: 42 bytes in 1 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 2,256 bytes in 18 blocks
suppressed: 0 bytes in 0 blocks
Reachable blocks (those to which a pointer was found) are not shown.
To see them, rerun with: --leak-check=full --show-reachable=yes
For counts of detected and suppressed errors, rerun with: -v
ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 282 from 9)
如果我删除了使用"new"实例化MyClass的部分,就不会出现内存泄漏。这让我相信C++类需要在PHP扩展中使用其他方法/宏进行实例化?
如果能提供任何帮助,我们将不胜感激。
要关闭它。问题是因为MyClass有一个未在实现文件中声明的私有静态成员变量。以上内容适用于在PHP扩展中实例化全局类,尽管它并不总是实例化的(有点来来去去)。将其保存为另一个问题:)
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 实例的全局初始化
- 全局变量的 C++ 后期实例化
- C++-防止全局实例化
- 如何在PHP扩展中实例化全局C++类
- 如何实例化全局智能指针变量
- 全局静态变量实例化行为
- 全局变量的实例化顺序