利用php調用so庫檔案中的代碼

來源:互聯網
上載者:User

某個功能被編譯到so檔案中,那麼如何通過php來調用它?一個方法是寫一個php模組(php
extension),在php中調用該模組內的函數,再通過該模組來調用so中的函數。下面做一個簡單的例子,使用的作業系統是RHEL5。

首先做一個簡單的so檔案:

/** * hello.c * To compile, use following commands: *   gcc -O -c -fPIC -o hello.o hello.c  *   gcc -shared -o libhello.so hello.o */int hello_add(int a, int b){    return a + b;}

然後將它編譯成.so檔案並放到系統中:

$ gcc -O -c -fPIC -o hello.o hello.c$ gcc -shared -o libhello.so hello.o$ su# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf# cp libhello.so /usr/local/lib# /sbin/ldconfig

寫段小程式來驗證其正確性:

/** * hellotest.c * To compile, use following commands: *   gcc -o hellotest -lhello hellotest.c */#i nclude <stdio.h>int main(){    int a = 3, b = 4;    printf("%d + %d = %d/n", a, b, hello_add(a,b));    return 0;}

編譯並執行:

$ gcc -o hellotest -lhello hellotest.c$ ./hellotest3 + 4 = 7

OK,下面我們來製作PHP模組。首先確保你安裝了 php-devel
包,沒有的話請自行從安裝光碟片上找。然後下載php原始碼。我使用的是php-5.2.3.tar.gz,解壓縮。

$ tar xzvf php-5.2.3.tar.gz$ cd php-5.2.3/ext

然後通過下面的命令建立一個名為 hello 的模組。

$ ./ext_skel --extname=hello

執行該命令之後它會提示你應當用什麼命令來編譯模組,可惜那是將模組整合到php內部的編譯方法。如果要編譯成可動態載入的
php_hello.so,方法要更為簡單。

$ cd hello

首先編輯 config.m4 檔案,去掉第16行和第18行的注釋(注釋符號為 dnl 。)

16:  PHP_ARG_ENABLE(hello, whether to enable hello support,17:  dnl Make sure that the comment is aligned:18:  [  --enable-hello           Enable hello support])

然後執行 phpize 程式,產生configure指令碼:

$ phpize

然後開啟 php_hello.h,在 PHP_FUNCTION(confirm_hello_compiled); 之下加入函式宣告:

PHP_FUNCTION(confirm_hello_compiled);   /* For testing, remove later. */PHP_FUNCTION(hello_add);

開啟 hello.c,在 PHP_FE(confirm_hello_compiled, NULL) 下方加入以下內容。

zend_function_entry hello_functions[] = {    PHP_FE(confirm_hello_compiled,  NULL)       /* For testing, remove later. */    PHP_FE(hello_add,   NULL)       /* For testing, remove later. */    {NULL, NULL, NULL}  /* Must be the last line in hello_functions[] */};

然後在 hello.c 的最末尾書寫hello_add函數的內容:

PHP_FUNCTION(hello_add){    long int a, b;    long int result;    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) {        return;    }    result = hello_add(a, b);    RETURN_LONG(result);}

儲存退出,編譯並安裝:

$ ./configure$ make LDFLAGS=-lhello$ su# cp modules/hello.so /usr/lib/php/modules

然後在 /var/www/html 下建立一個 hello.php 檔案,內容如下:

<?php    dl("hello.so");    echo hello_add(3, 4);?>

然後在瀏覽器中開啟hello.php檔案,如果顯示7,則說明函數調用成功了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.