c - Can I pass the string in PHP extension by reference with separating from other variables? -
i have example code:
zend_begin_arg_info(arginfo_refstring, 0) zend_arg_info(1, s1) zend_end_arg_info() const zend_function_entry refstring_functions[] = { php_fe(refstring, arginfo_refstring) php_fe_end }; php_function(refstring) { char *s1; int s1_len; if (zend_parse_parameters(zend_num_args() tsrmls_cc, "s", &s1, &s1_len) == failure) { return; } s1[0] = 'x'; }
and php code:
$s1 = 'hello'; $s2 = $s1; refstring($s1); var_dump($s1, $s2);
i expect:
string(5) "xello" string(5) "hello"
but got:
string(5) "xello" string(5) "xello"
how can separate
$s2
$s1
, keep ability change$s1
inside function?
i known separate_zval , co., did not help...
this happens because of mechanism called copy on write.
after lines:
$s1 = 'hello'; $s2 = $s1;
$s1
, $s2
both independent variables (zvals), point same(!) data in memory - because both share same value, meaning none of them has been changed far.
if would:
$s1 = 'foo';
... php internally update zval behind $s1
in way it's value points different portion of memory.
however, since modifying value in extension function, function need take care on itself:
php_function(refstring) { zval *s1; char *string; if (zend_parse_parameters(zend_num_args() tsrmls_cc, "z", &s1) != success ) { return; } // copy value before writing string = strdup(s1->value.str.val); string[0] = 'x'; zval_string(s1, string, 1); }
note i'm using zval *
rather using pure string input parameter.
further note that, above function works expected. however, i'm not sure if there macro purpose can used more elegantly.
Comments
Post a Comment