2009-08-09 76 views
18

自20世紀80年代和90年代以來,我沒有使用C語言進行自己的實驗。我希望能夠再次拿起它,但是這次通過在它上面創建小的東西,然後將它加載到Linux上的PHP中。如何在Linux GCC的C語言中構建我的第一個PHP擴展?

有沒有人有一個非常簡短的教程,讓我在C中作爲一個共享對象擴展在php.ini中加載一個foo()函數?我假設我需要使用GCC,但不知道我的Ubuntu Linux工作站上還需要什麼來完成這個任務,或者如何編寫這些文件。

我見過的一些例子展示瞭如何在C++中完成它,或者將它顯示爲必須編譯到PHP中的靜態擴展。我不想這樣做 - 我想把它作爲一個C擴展,而不是C++,並通過php.ini加載它。

我想到了一些我稱之爲foo('hello')的東西,如果它看到傳入的字符串是'hello',它會返回'world'。

舉例來說,如果這個寫於100%的PHP,功能可能是:

function foo($s) { 
    switch ($s) 
    case 'hello': 
     return 'world'; 
     break; 
    default: 
     return $s; 
    } 
} 

回答

6

擴展這個例子。

<?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); 
} 

建立你的擴展 $ phpize $ ./configure --enable-hello $ make

運行這些命令後,你應該有一個hello.so

延長= hello.so到php.ini來觸發它。

php -r 'echo hello_world();' 

你做。;-)

爲簡單的方法來只是嘗試ZEPHIR琅構建PHP擴展與

namespace Test; 

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

編譯的知識較少讀更多here

它與zephir和獲得測試擴展

+0

請提供文檔網址。 – 2017-04-14 19:26:00

+0

已經提供 – 2017-04-15 04:56:38

2

試圖Saurabh的實例用PHP 7.1.6 mple,發現需要進行一些小的改動:

  • 變化function_entryzend_function_entry
  • 更換RETURN_STRING("Hello World", 1)RETURN_STRING("Hello World")

這是一個很好的例子代碼開始PHP擴展開發!謝謝!