views:

238

answers:

2

I'm writing a PHP extension that takes a reference to a value and alters it. Example PHP:

$someVal = "input value";
TestPassRef($someVal);
// value now changed

What's the right approach?

+1  A: 

The following works and seems not to leak memory:

PHP_FUNCTION(TestPassRef)
{
    zval *pZVal = NULL;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &pZVal) == FAILURE)
    {
        return;
    }

    convert_to_null(pZVal);  // Destroys the value that was passed in

    ZVAL_STRING(pZVal, "some string that will replace the input", 1);
}

Before adding the convert_to_null it would leak memory on every call. I'm not sure this is the "correct" way, however.

therefromhere
A: 

Not really an answer, and you probably know already, but I feel inclined to point out that passing by-ref is an un-intuitive and somewhat exotic way to return data in PHP. I would suggest that you return an array, if you need to return multiple values.

troelskn