how to return an array of c++ objects
[email protected] ("John Hayes") Wed, 19 May 2010 15:15:16 -0400
| Newsgroups | php.pecl.dev |
|---|---|
| Message-ID | <018001caf787$9dc3c920$d94b5b60$@com> |
I have a Graph object which contains a std::Map<int, Node*> nodes .
graph->getNodes() just returns this->nodes . It is this function I'm
attempting to wrap in a PHP extension.
I have already exposed the Graph and Node objects to userspace and need to
return an array of Node objects. However, I'm getting a segfault with my
current code and can't figure out why. Can someone spot my mistake? Here's
the relevant code (please let me know if I forget something useful):
---code---
struct node_object {
zend_object std;
Node *node;
};
zend_class_entry *node_ce;
/* snip... */
PHP_METHOD(Graph, getNodes)
{
Graph *graph;
graph_object *obj =
(graph_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
graph = obj->graph;
node_object* n;
zval* node_zval;
if (obj == NULL) {
RETURN_NULL();
}
if (object_init_ex(node_zval, node_ce) != SUCCESS) {
RETURN_NULL();
}
std::map<int, Node*> nodes = graph->getNodes();
array_init(return_value);
for (std::map<int, Node*>::iterator i = nodes.begin(); i !=
nodes.end(); ++i) {
php_printf("X");
n = (node_object*) zend_object_store_get_object(node_zval
TSRMLS_CC);
n->node = i->second;
add_index_zval(return_value, i->first, node_zval);
}
php_printf("]");
}
--- end code ---
--- output ---
$ php -r '$g = new Graph(); $g->getNodes();'
XX]Segmentation fault
--- end output ---
(As you can see, the two-node long map is being traversed, the function
exits, then the segfault.)
Thanks very much for your help.
John