php調用C代碼的方法詳解

來源:互聯網
上載者:User

在php程式中需要用到C代碼,應該是下面兩種情況:

1 已有C代碼,在php程式中想直接用2 由於php的效能問題,需要用C來實現部分功能針對第一種情況,最合適的方法是用system調用,把現有C代碼寫成一個獨立的程式。參數通過命令列或者標準輸入傳入,結果從標準輸出讀出。其次,稍麻煩一點的方法是C代碼寫成一個daemon,php程式用socket來和它進行通訊。重點講講第二種情況,雖然沿用system調用的方法也可以,但是想想你的目的是最佳化效能,那麼頻繁的起這麼多進程,當然會讓效能下降。而寫daemon的方法固然可行,可是繁瑣了很多。我的簡單測試,同樣一個演算法,用C來寫比用php效率能提高500倍。而用php擴充的方式,也能提高90多倍(其中的效能損失在了參數傳遞上了吧,我猜)。所以有些時候php擴充就是我們的最佳選擇了。這裡我著重介紹一下用C寫php擴充的方法,而且不需要重新編譯php。首先,找到一個php的源碼,php4或者php5版本的都可以,與你目標平台的php版本沒有關係。在源碼的ext目錄下可以找到名為ext_skel的指令碼在這個目錄下執行#./ext_skel --extname=hello這時產生了一個目錄 hello,目錄下有幾個檔案,你只需要關心這三個:config.m4 hello.c php_hello.h把這個目錄拷備到任何你希望的地方,cd進去,依次執行#phpize#./configure#make什麼也沒發生,對吧?這是因為漏了一步,開啟config.m4,找到下面dnl If your extension references something external, use with:...dnl Otherwise use enable:...這是讓你選擇你的擴充使用with還是enable,我們用with吧。把with那一部分取消注釋。如果你和我一樣使用vim編輯器,你就會很容易發現dnl三個字母原來是表示注釋的呀(這是因為vim預設帶了各種檔案格式的文法著色包)我們修改了config.m4後,繼續#phpize#./configure#make這時,modules下面會產生hello.so和hello.la檔案。一個是動態庫,一個是靜態庫。你的php擴充已經做好了,儘管它還沒有實現你要的功能,我先說說怎麼使用這個擴充吧!ext_skel為你產生了一個hello.php裡面有調用樣本,但是那個例子需要你把hello.so拷貝到php的擴充目錄中去,我們只想實現自己的功能,不想打造山寨版php,改用我下面的方法來載入吧:
  1. if(!extension_loaded("hello")) {
  2.         dl_local("hello.so");
  3. }
  4. function dl_local( $extensionFile ) {
  5.         //make sure that we are ABLE to load libraries
  6.         if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
  7.                 die( "dh_local(): Loading extensions is not permitted./n" );
  8.         }
  9.         //check to make sure the file exists
  10.         if( !file_exists(dirname(__FILE__) . "/". $extensionFile ) ) {
  11.                 die( "dl_local(): File '$extensionFile' does not exist./n" );
  12.         }
  13.         //check the file permissions
  14.         if( !is_executable(dirname(__FILE__) . "/". $extensionFile ) ) {
  15.                 die( "dl_local(): File '$extensionFile' is not executable./n" );
  16.         }
  17.         //we figure out the path
  18.         $currentDir = dirname(__FILE__) . "/";
  19.         $currentExtPath = ini_get( "extension_dir" );
  20.         $subDirs = preg_match_all( "////" , $currentExtPath , $matches );
  21.         unset( $matches );
  22.         //lets make sure we extracted a valid extension path
  23.         if( !(bool)$subDirs ) {
  24.                 die( "dl_local(): Could not determine a valid extension path [extension_dir]./n" );
  25.         }
  26.         $extPathLastChar = strlen( $currentExtPath ) - 1;
  27.         if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
  28.                 $subDirs--;
  29.         }
  30.         $backDirStr = ""; 
  31.         for( $i = 1; $i <= $subDirs; $i++ ) {
  32.                 $backDirStr .= "..";
  33.                 if( $i != $subDirs ) {
  34.                   $backDirStr .= "/";
  35.                 }
  36.         }
  37.         //construct the final path to load
  38.         $finalExtPath = $backDirStr . $currentDir . $extensionFile;
  39.         //now we execute dl() to actually load the module
  40.         if( !dl( $finalExtPath ) ) {
  41.                 die();
  42.         }
  43.         //if the module was loaded correctly, we must bow grab the module name
  44.         $loadedExtensions = get_loaded_extensions();
  45.         $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];
  46.         //lastly, we return the extension name
  47.         return $thisExtName;
  48. }//end dl_local()

這樣的好處是你的php擴充可以隨你的php代碼走,綠色擴充。

隨後一個讓人關心的問題是,如何添加函數、實現參數傳遞和傳回值添加函數步驟如下:php_hello.h:PHP_FUNCTION(confirm_hello_compiled);// 括弧裡面填寫函數名hello.czend_function_entry hello_functions[] = {    PHP_FE(confirm_hello_compiled,  NULL)       /* 這裡添加一行 */    {NULL, NULL, NULL}  /* Must be the last line in hello_functions[] */};PHP_FUNCTION(confirm_hello_compiled) {// 這裡寫函數體}要實現的函數原型其實都一個樣,用宏PHP_FUNCTION來封裝了一下,另外呢,在hello_functions裡面添加了一行資訊,表示你這個模組中有這個函數了。那麼都是一樣的函數原型,如何區分傳回值與參數呢?我給一個例子:
  1. PHP_FUNCTION(hello_strdiff)
  2. {
  3.     char *r1 = NULL, *r2 = NULL;
  4.     int n = 0, m = 0;
  5.     if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &r1, &n, &r2, &m) == FAILURE) {
  6.         return;
  7.     }
  8.     while(n && m && *r1 == *r2) {
  9.         r1++;
  10.         r2++;
  11.         n--;
  12.         m--;
  13.     }
  14.     if(n == 0) RETURN_LONG(m);
  15.     if(m == 0) RETURN_LONG(n);
  16.     int d[n+1][m+1];
  17.     int cost;
  18.     int i,j;
  19.     for(i = 0; i <= n; i++) d[i][0] = i;
  20.     for(j = 0; j <= m; j++) d[0][j] = j;
  21.     for(i = 1; i <= n; i++) {
  22.         for(j = 1; j <= m; j++) {
  23.             if(r1[i-1] == r2[j-1]) cost = 0;
  24.             else cost = 1;
  25.             int a = MIN(d[i-1][j]+1,d[i][j-1]+1);
  26.             a = MIN(a, d[i-1][j-1]+cost);
  27.             d[i][j] = a;
  28.         }
  29.     }
  30.     RETURN_LONG(d[n][m]);
  31. }

這是一個求兩個字串差異度的演算法,輸入參數兩個字串,返回整型。

參數的傳遞看這裡zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &r1, &n, &r2, &m)把這個當成是scanf來理解好了。類型說明見下表:

Boolean b zend_bool
Long l long
Double d double
String s char*, int
Resource r zval*
Array a zval*
Object o zval*
zval z zval*

如果想實現選擇性參數的話,例如一個字串,一個浮點,再加一個可選的bool型,可以用"sd|b"來表示。

和scanf有一點不同的是,對於字串,你要提供兩個變數來儲存,一個是char *,存字串的地址,一個int,來存字串的長度。這樣有必要的時候,你可以安全的處理位元據。
那麼傳回值怎麼辦呢?使用下面一組宏來表示:RETURN_STRING
RETURN_LONG
RETURN_DOUBLE
RETURN_BOOL
RETURN_NULL
注意RETURN_STRING有兩個參數當你需要複製一份字串時使用RETURN_STRING("Hello World", 1);
否則使用RETURN_STRING(str, 0);
這裡涉及到了模組中記憶體的分配,當你申請的記憶體需要php程式中去釋放的話,請參照如下表

Traditional Non-Persistent Persistent
malloc(count)
calloc(count, num)
emalloc(count)
ecalloc(count, num)
pemalloc(count, 1)*
pecalloc(count, num, 1)
strdup(str)
strndup(str, len)
estrdup(str)
estrndup(str, len)
pestrdup(str, 1)
pemalloc() & memcpy()
free(ptr) efree(ptr) pefree(ptr, 1)
realloc(ptr, newsize) erealloc(ptr, newsize) perealloc(ptr, newsize, 1)
malloc(count * num + extr)** safe_emalloc(count, num, extr) safe_pemalloc(count, num, extr)

一般我們使用Non-Persistent中列出的這些好了。


基本上就是這樣,可以開始寫一個php的擴充了。從我目前的應用來看,能操縱字串就夠用了,所以我就只能介紹這麼多了,如果要詳細一點的呢,例如php數組怎麼處理,可以參考http://devzone.zend.com/node/view/id/1022
更詳細的呢,可以參考php手冊中的《Zend API:深入 PHP 核心》一章不過這些資料都是英文的。

 轉自:http://blog.csdn.net/oyd/article/details/3168417

 

另外可參考:http://www.phpchina.com/index.php?action-viewthread-tid-26870

http://blog.csdn.net/xiaocon/article/details/388953

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.