views:

21

answers:

1

Hi all, I want to convert Zval to char*. how do i do that in my php extension?

+1  A: 

It the zval represents a string, you can use Z_STRVAL (or Z_STRVAL_P/Z_STRVAL_PP if you have a zval*/zval**).

Otherwise, you may have to convert the zval before :

zval *var;
char *cstr;
int cstrlen;
/* ... */
if (Z_TYPE_P(var) != IS_STRING) {
    convert_to_string(var);
}
cstr = Z_STRVAL_P(var);
cstrlen = Z_STRLEN_P(var);

If you don't want to change the original zval and you want to change the resulting C string, you can do:

zval *var, *varcopy;
char *cstr;
int cstrlen;

if (Z_TYPE_P(var) != IS_STRING) {
    ALLOC_INIT_ZVAL(varcopy);
    *varcopy = *var;
    INIT_PZVAL(varcopy); /* reset refcount and clear is_ref */
    zval_copy_ctor(varcopy);
    convert_to_string(varcopy);
} else {
    varcopy = var;
}

cstrlen = Z_STRLEN_P(varcopy);
cstr = estrndup(Z_STRVAL_P(varcopy), cstrlen);

if (varcopy != var) {
    zval_ptr_dtor(&varcopy);
}
Artefacto