Passing a variable by reference into a PHP extension

末鹿安然 提交于 2019-12-22 04:28:05

问题


I'm writing a PHP extension that takes a reference to a value and alters it. Example PHP:

$someVal = "input value";
TestPassRef($someVal);
// value now changed

What's the right approach?


回答1:


Edit 2011-09-13: The correct way to do this is to use the ZEND_BEGIN_ARG_INFO() family of macros - see Extending and Embedding PHP chapter 6 (Sara Golemon, Developer's Library).

This example function takes one string argument by value (due to the ZEND_ARG_PASS_INFO(0) call) and all others after that by reference (due to the second argument to ZEND_BEGIN_ARG_INFO being 1).

const int pass_rest_by_reference = 1;
const int pass_arg_by_reference = 0;

ZEND_BEGIN_ARG_INFO(AllButFirstArgByReference, pass_rest_by_reference)
   ZEND_ARG_PASS_INFO(pass_arg_by_reference)
ZEND_END_ARG_INFO()

zend_function_entry my_functions[] = {
    PHP_FE(TestPassRef, AllButFirstArgByReference)
};

PHP_FUNCTION(TestPassRef)
{
    char *someString = NULL;
    int lengthString = 0;
    zval *pZVal = NULL;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &someString, &lengthString, &pZVal) == FAILURE)
    {
        return;
    }

    convert_to_null(pZVal);  // Destroys the value that was passed in

    ZVAL_STRING(pZVal, "some string that will replace the input", 1);
}

Before adding the convert_to_null it would leak memory on every call (I've not whether this is necessary after adding ZENG_ARG_INFO() calls).



来源:https://stackoverflow.com/questions/678026/passing-a-variable-by-reference-into-a-php-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!