How Do I Build My First PHP Extension in C on Linux GCC?

后端 未结 2 1232
余生分开走
余生分开走 2020-12-13 20:26

I haven\'t used C since the 1980s and 1990s with my own experimentation. I\'d like to be able to pick it up again, but this time by building small things in it and then load

相关标签:
2条回答
  • 2020-12-13 20:44

    extension for this example.

    <?php
        function hello_world() {
            return 'Hello World';
        }
    ?>
    
    ### config.m4
    PHP_ARG_ENABLE(hello, whether to enable Hello
    World support,
    [ --enable-hello   Enable Hello World support])
    if test "$PHP_HELLO" = "yes"; then
      AC_DEFINE(HAVE_HELLO, 1, [Whether you have Hello World])
      PHP_NEW_EXTENSION(hello, hello.c, $ext_shared)
    fi
    
    ### php_hello.h
    #ifndef PHP_HELLO_H
    #define PHP_HELLO_H 1
    #define PHP_HELLO_WORLD_VERSION "1.0"
    #define PHP_HELLO_WORLD_EXTNAME "hello"
    
    PHP_FUNCTION(hello_world);
    
    extern zend_module_entry hello_module_entry;
    #define phpext_hello_ptr &hello_module_entry
    
    #endif
    
    #### hello.c
    #ifdef HAVE_CONFIG_H
    #include "config.h"
    #endif
    #include "php.h"
    #include "php_hello.h"
    
    static function_entry hello_functions[] = {
        PHP_FE(hello_world, NULL)
        {NULL, NULL, NULL}
    };
    
    zend_module_entry hello_module_entry = {
    #if ZEND_MODULE_API_NO >= 20010901
        STANDARD_MODULE_HEADER,
    #endif
        PHP_HELLO_WORLD_EXTNAME,
        hello_functions,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
    #if ZEND_MODULE_API_NO >= 20010901
        PHP_HELLO_WORLD_VERSION,
    #endif
        STANDARD_MODULE_PROPERTIES
    };
    
    #ifdef COMPILE_DL_HELLO
    ZEND_GET_MODULE(hello)
    #endif
    
    PHP_FUNCTION(hello_world)
    {
        RETURN_STRING("Hello World", 1);
    }
    

    Building Your Extension $ phpize $ ./configure --enable-hello $ make

    After running each of these commands, you should have a hello.so

    extension=hello.so to your php.ini to trigger it.

     php -r 'echo hello_world();'
    

    you are done .;-)

    read more here

    for Easy way to just try zephir-lang to build php extension with less knowledge of

    namespace Test;
    
    /**
     * This is a sample class
     */
    class Hello
    {
        /**
         * This is a sample method
         */
        public function say()
        {
            echo "Hello World!";
        }
    }
    

    compile it with zephir and get test extension

    0 讨论(0)
  • 2020-12-13 20:53

    Tried Saurabh's example with PHP 7.1.6 and found some minor changes were required:

    • Change function_entry to zend_function_entry
    • Replace RETURN_STRING("Hello World", 1) with RETURN_STRING("Hello World")

    This is a great example code to start PHP extension development! Thank you!

    0 讨论(0)
提交回复
热议问题