I'm learning how to write PHP extensions and have come across a problem I haven't been able to find an answer to on the Interwebs. I'm trying to use C++ classes from my PHP extension, and although it seems to be working from the CLI, valgrind reports problems.
My globals are as follows:
ZEND_BEGIN_MODULE_GLOBALS(myext)
MyClass *myClass;
ZEND_END_MODULE_GLOBALS(myext)
This class is instantiated as an extension global follows:
static void myext_init_globals(zend_myext_globals *myext_globals TSRMLS_DC)
{
myext_globals->myClass = (MyClass*)pemalloc(sizeof(MyClass), 0);
MyClass *myClass = new (myext_globals->myClass) MyClass();
}
and it is freed using:
static void myext_destroy_globals(zend_myext_globals *myext_globals TSRMLS_DC)
{
pefree(myext_globals->myClass, 0);
}
MyClass.h:
class MyClass
{
private:
std::string strSomeText;
public:
MyClass();
~MyClass();
};
MyClass.cpp:
MyClass::MyClass()
{
strSomeText = "ABC"; // <-- this causes valgrind errors!
}
I have found that if I may strSomeText a static member variable, then valgrind reports no errors.
Also, if I try to allocate memory in the MyClass constructor and then delete or free it in the MyClass destructor, valgrind again reports leaks.
Ideally, I'd like to be able to grab "any ol' class" and just use it without having to make significant changes to it just to get it working as a PHP extension global.
UPDATE: My question is, how do you use a "generic" C++ class that uses things like std::string, or that allocates/de-allocated memory (either in the constructor/destructor, or a member method)? I have found that if I include php.h in MyClass and then allocate memory using emalloc/pemalloc and then de-allocate memory with efree and pefree, then things work and there are no memory leaks reported by valgrind. However, this is not ideal. There must be a way to use a "generic" C++ class (i.e. one that you don't have to refactor to be PHP extension friendly) as a PHP extension global (as in my example above).