Return same array (zval) as passed in to a function

316 views Asked by At

I tried to create a new function in my extension which takes an array as parameter adds an entry to that same instance of the array and returns that instance again.

So this is the code so far:

PHP_FUNCTION(make_array)
{
        // array_init(return_value); // Also Tried to transform default NULL to array

        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &return_value) == FAILURE) {
                RETURN_FALSE;
        }

        add_assoc_long(return_value, "answer", 42);

        return;
}

But I only get NULL as return value or if I uncomment array_init(return_value); the return_value is an empty array.

So why is that behavior? And what did I understand wrong?

1

There are 1 answers

3
Ja͢ck On BEST ANSWER

Using return_value directly as part of a ZPP argument is typically not done (actually, never); it's commonly done by introducing a regular zval * container and then RETURN_ZVAL or RETVAL_ZVAL macro is used:

PHP_FUNCTION(make_array)
{
    zval *arr;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) {
        return;
    }

    add_assoc_long(arr, "answer", 42);
    RETURN_ZVAL(arr, 0, 0);
}