Summary of Extended Writing of php

  • 2021-12-11 07:09:22
  • OfStack

Why use C extension

C is statically compiled and executes much more efficiently than PHP code. The same operation code, using C to develop, the performance will be hundreds of times higher than PHP. IO operations are like CURL, because the time consumption is mainly on IOWait, and C extension has no obvious advantage.

In addition, C extension is loaded when the process starts, PHP code can only operate the data of Request life cycle, and C extension can operate in a wider range.

Step 1

Download the source code for PHP, such as php-5. 4.16. Extract and enter the php-5. 4.16\ ext directory. Enter. /ext_skel-extname=myext, myext is the name of the extension, which generates the myext directory.

ext_skel is an official tool provided by PHP for generating php extension skeleton code.

cd myext. You can see several files, such as php_myext. h, myext. c, config. m4, and so on. config. m4 is a configuration file for the AutoConf tool to modify various compilation options.

Step 2

Modify config. m4 to set the


dnl PHP_ARG_WITH(myext, for myext support,

dnl Make sure that the comment is aligned:

dnl [ --with-myext       Include myext support])

Modify to


PHP_ARG_WITH(myext, for myext support,

[ --with-myext       Include myext support])

There is also one below-enable-myext, which means compiling into the php kernel. with is loaded as a dynamic link library.

Step 3

Modify php_myext. h to see PHP_FUNCTION (confirm_myext_compiled); This is the extension function declaration section, which can add one line of PHP_FUNCTION (myext_helloworld); Indicates that an extension function of myext_helloworld is declared.

Then modify myext. c, which is the implementation part of the extension function.


const zend_function_entry myext_functions[] = {

    PHP_FE(confirm_myext_compiled, NULL)      /* For testing, remove later. */

    PHP_FE(myext_helloworld, NULL)

    PHP_FE_END   /* Must be the last line in myext_functions[] */

};

The code here is to register the function pointer to the Zend engine, adding one line of PHP_FE (myext_helloworld, NULL) (without a semicolon).

Step 4

Add the execution code for myext_helloworld at the end of myext. c.


PHP_FUNCTION(myext_helloworld)

{

    char *arg = NULL;

  int arg_len, len;

  char *strg;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {

    return;

  }

  php_printf("Hello World!\n");

  RETRUN_TRUE;

}

zend_parse_parameters is used to accept the parameters passed in by PHP, and the RETURN_XXX macro is used to return data to PHP.

Step 5

Execute phpize,./configure, make, make install in turn under the myext directory. Then modify php. ini and add extension=myext. so

Execute php-r "myext_helloworld ('test');" Output hello world!


Related articles: