开发者

Value returned from PHP extension function is NULL

I've stumbled upon an interesting case while de开发者_开发问答veloping an extension for PHP. In the extension code I have:

PHP_FUNCTION(foo)
{
   ....
   php_debug_zval_dump(return_value, 1);
}

In the PHP code:

$v = foo();
debug_zval_dump($v);

When running the above, I get:

string(19) "Mouse configuration" refcount(1)
NULL refcount(2)

What can be the reason that the value isn't passed properly from the extension?

Thanks!


It's not that strange.

For instance, if you did return_value = some_string_zval; you would be changing only the local variable. php_debug_zval_dump would work, but it would have no effect outside the function. You have to actively copy the zval, e.g. with:

ZVAL_COPY_VALUE(return_value, my_string_zval_p);
zval_copy_ctor(return_value);

The only case you could return from an internal function merely copying a pointer instead of copying data was if that function returned by reference. In that case, you're given a zval**.


You're getting a NULL because debug_zval_dump() has a built-in echo feature and you cannot set an echo to a variable. So your $v = foo() is actually giving you $v = "". The reason you're getting a refcount of 2 for an empty variable is because of inherent PHP optimization.

Read about that here: http://us3.php.net/manual/en/function.debug-zval-dump.php

So to return your value properly you can:

  1. Suppress the built-in echo by writing the echo to a buffer
  2. Set the buffer result to a variable
  3. Run your second debug_zval_dump() on that (not NULL) variable

Here's how it works:

function myfunc($foo)
{
  debug_zval_dump($foo, 1);
}
ob_start();
/*
starts the output buffer which will catch all code instead of echoing it to page
*/
myfunc('Mouse configuration');

$v = ob_get_contents();
/*
writes the buffer which contains your f(x) results to a var
*/

ob_end_clean();//clears the buffer

debug_zval_dump($v);//will echo non-null value

The code will result with this:

string(65) "string(19) "Mouse configuration" refcount(3) long(1) refcount(1) " refcount(2)

I have no idea what this code is meant to do but Good Luck anyways. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜