如何在PHP扩展中实例化全局C++类

How to instantiate a global C++ class within a PHP extension?

本文关键字:实例化 全局 C++ 扩展 PHP      更新时间:2023-10-16

我正在将一个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扩展中实例化全局类,尽管它并不总是实例化的(有点来来去去)。将其保存为另一个问题:)