Convert Zval to char*
Asked Answered
S

1

5

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

Sidran answered 31/8, 2010 at 4:54 Comment(0)
H
15

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);
}
Holloman answered 31/8, 2010 at 23:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.