Search code examples
phpcphp-internals

How do i return an array from php extension?


How do I return an array from a php extension method? This is what I have so far:

struct myClass_object
{
    zend_object std;
    MyClass *myClassInstance;
};

PHP_METHOD(MyClass, getMyArray)
{
    zval *obj = getThis();
    MyClass *myClass = (myClass_object *) zend_object_store_get_object (obj TRMLS_CC)->myClassInstance;
    if (myClass != NULL)
    {
        int length = myClass->getMyArrayLength();
        int *myArray = myClass->getMyArray();
        // return myArray!
    }
    RETURN_NULL();
}

Solution

  • After examining some php source files I was able to return an array like this:

    PHP_METHOD(MyClass, getMyArray)
    {
        zval *obj = getThis();
        MyClass *myClass = (myClass_object *) zend_object_store_get_object (obj TRMLS_CC)->myClassInstance;
        if (myClass != NULL)
        {
            int length = myClass->getMyArrayLength();
            int *myArray = myClass->getMyArray();
            array_init(return_value);
            for (int i = 0; i < length; i++) add_index_long(return_value, i, myArray[i]);
            return;
        }
        RETURN_NULL();
    }