简体   繁体   English

PHP扩展函数返回的值为NULL

[英]Value returned from PHP extension function is NULL

I've stumbled upon an interesting case while developing an extension for PHP. 在开发PHP扩展时,我偶然发现了一个有趣的案例。 In the extension code I have: 在扩展代码中,我有:

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

In the PHP code: 在PHP代码中:

$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! 谢谢!

You're getting a NULL because debug_zval_dump() has a built-in echo feature and you cannot set an echo to a variable. 由于debug_zval_dump()具有内置的echo功能,并且无法将echo设置为变量,因此您将获得NULL。 So your $v = foo() is actually giving you $v = "". 因此,您的$ v = foo()实际上是给您$ v =“”。 The reason you're getting a refcount of 2 for an empty variable is because of inherent PHP optimization. 空变量的引用计数为2的原因是固有的PHP优化。

Read about that here: http://us3.php.net/manual/en/function.debug-zval-dump.php 在这里阅读有关内容: 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 在该变量(非NULL)上运行第二个debug_zval_dump()

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) string(65)“ string(19)”鼠标配置“ refcount(3)long(1)refcount(1)” refcount(2)

I have no idea what this code is meant to do but Good Luck anyways. 我不知道这段代码是做什么的,但无论如何,祝你好运。 :) :)

It's not that strange. 这并不奇怪。

For instance, if you did return_value = some_string_zval; 例如,如果您确实做了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. php_debug_zval_dump可以工作,但是在函数外部不会起作用。 You have to actively copy the zval, eg with: 您必须主动复制zval,例如:

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** . 在这种情况下,您会得到zval**

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM