PHP擴展開發(一)--DEMO

##入門php

1.下載PHP源碼(個人版本是5.6.13)
2.常規編譯安裝  [能夠看我之前的blog](http://my.oschina.net/lwl1989/blog/511295)
3.使用ext_skel
```
    cd phpsrc/ext
    ./ext_skel --extname=name  // name 是指你要寫得擴展的名字,下文咱們都是t2
```

出現提示mysql

1.  $ cd ..
2.  $ vi ext/t2/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-t2
5.  $ make
6.  $ ./sapi/cli/php -f ext/t2/t2.php
7.  $ vi ext/t2/t2.c
8.  $ make

根據提示進行操做 其中第二步 咱們應該修改config.m4的十、十一、12行 去除掉dnl[個人理解是ZEND一種註釋的方案]sql

到這個時候,咱們就能夠進行編譯安裝了api

/usr/local/php/bin/phpize   //執行phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make 
make install

在php.ini裏開啓 t2.so文件 你的模塊就加載好了 查看php -m 能夠發現t2模塊已經被加載函數

##編碼(HELLO WORLD) 可是目前而言,這個擴展是沒有任何功能的。 因而咱們須要加入新的功能。ui

這時,咱們能夠對t2.c文件進行編寫(固然你也能夠寫在別的文件裏,在t2.c裏面include)編碼

PHP_FUNCTION(t2_hello)
{
    printf("hello world\n");
}

這樣從新編譯後,運行 php -r "t2_hello();"是不行的,爲何呢?.net

由於咱們沒有將t2_hello載入到函數列表指針

原型:code

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;

參數 描述 fname 提供給PHP中調用的函數名。例如mysql_connect handler 負責處理這個接口函數的指針。 func_arg_types 標記參數。能夠設置爲NULL

咱們在生成的中加入一行

static const zend_function_entry t2_functions[] = {
    //在這加入
     {NULL, NULL, NULL}
}
PHP_FE(t2_hello,  NULL)

注意,zend_function_entry的最後一項必定是{NULL, NULL, NULL},Zend引擎就是靠這個判斷導出函數列表是否完畢的。

而後從新編譯,運行php -r "t2_hello();" 這時,咱們的hello world!到此完成了

時間不太多,下次咱們再說關於變量和參數值傳遞的處理還有幾個模塊的魔術方法(zend_module_entry)。

相關文章
相關標籤/搜索