【发布时间】:2015-02-09 17:47:37
【问题描述】:
我将 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) 进行 valgrind 时,我得到了泄漏:
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 扩展中使用其他方法/宏进行实例化?
我们将不胜感激任何有助于阐明这一点的帮助。
【问题讨论】:
标签: c++ memory-leaks valgrind php-extension