Vanessa Deagan
Vanessa Deagan

Reputation: 427

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

I'm instantiating a C++ class as a global inside a PHP extension. It works, however, valgrind is reporting a definite memory leak.

In my php_myext.h, I declare the global using:

 ZEND_BEGIN_MODULE_GLOBALS(myext)
  MyClass *myClass;
 ZEND_END_MODULE_GLOBALS(myext)

Inside my PHP_MINIT_FUNCTION I set the initializer and destructor for globals:

ZEND_INIT_MODULE_GLOBALS(myext, myext_init_globals, myext_destroy_globals);

Then my initializer and destructor are implemented as follows:

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
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;
}

I have exposed MyClass::test() method to PHP using the following:

static PHP_METHOD(MyExt, test)
{
  RETURN_STRING(MYEXT_G(myClass)->test().c_str(), 1);
}

Everything works fine from my PHP script:

<?php echo MyExt::test(); ?>

However, when I valgrind my test script (test.php), I get a leak:

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)

If I remove the parts that instantiate MyClass using "new", there are no memory leaks. This leads me to believe C++ classes need to be instantiated inside a PHP extension using some other method/macros?

Any help that sheds light on this would really be appreciated.

Upvotes: 0

Views: 98

Answers (1)

Vanessa Deagan
Vanessa Deagan

Reputation: 427

Going to close this. The problem was because MyClass has a private static member variable that wasn't declared within the implementation file. The above works for instantiating a global class within a PHP extension, although it's not always instantiated (kind of comes and goes). Will save that for another question :)

Upvotes: 1

Related Questions