Handle Arrays PHP Extension

Wednesday, July 2, 2014

I am working on a project that involves writing PHP extensions in C so that they can be called upon by regular PHP. I am making progress, however I am a bit stumped when it comes to handling arrays. Here is the code for the current function I am working on: PHP_FUNCTION(hello)



PHPFUNCTION(hello)
{
zval *arr;
HashTable *arr_hash;
int array_count, i;

if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE)
RETURN_NULL();

arr_hash = Z_ARRVAL_P(arr);
array_count = zend_hash_num_elements(arr_hash);

php_printf("The array contains %d elements<br>", array_count);

for(i = 0; i < array_count; ++i)
php_printf("%d<br>", Z_LVAL(*(arr+i)));

RETURN_TRUE;
}


All this code is supposed to be doing for the time being is outputting the size of the array and then iterate through the variables within it. The PHP code that I am using to call it is:



<?php
$me = array(100, 200, 300);
hello($me);
?>


At the moment it outputs:



The array contains 3 elements
58311664
0
0


I don't know if this is important because it obviously is compiling, but this is the rest of the code in that C file and it is located above the function:



#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"

extern zend_module_entry hello_module_entry;
#define phpext_hello_ptr &hello_module_entry

PHP_FUNCTION(hello);

static function_entry hello_functions[] = {
PHP_FE(hello, NULL)
{NULL, NULL, NULL}
};

zend_module_entry hello_module_entry = {
STANDARD_MODULE_HEADER,
"hello",
hello_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
"0.1",
STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(hello)


Also, I am on Windows. I did not include my .w32 file as I do not think it is required, but it can be provided on request if needs be. Thanks.







http://ift.tt/1rh9l5E