星期二, 5月 24, 2016

[PHP] php-extension: 範例練習

經過前幾次的練習與說明,筆記一下因為自已的需求測試的範例


範例: 從自已建一個額外的C語言的檔案呼叫



1.修正一下config.m4指定載入額外的C語言

dnl config.m4 for extension


PHP_ARG_ENABLE(foo, whether to enable foo extension support,
  [--enable-foo Enable foo extension support])

dnl 檢測extension是否已被啟動
if test $PHP_FOO != "no"; then

 AC_MSG_CHECKING("start to enable extension");

  dnl PHP_NEW_EXTENSION(foo, php_foo.c, $ext_shared)

  dnl 注意多引用了自定義C語言func
    PHP_NEW_EXTENSION(foo, php_foo.c hello_world_c.c, $ext_shared)


fi


2.先建立自已的C的實作與標頭檔
hello_world_c.h, hello_world_c.c

int hello_world_c_add(int, int);


/*Hello World program*/

#include <stdio.h>
#include "hello_world_c.h"

int hello_world_c_add(int a,int b){
 int sum = 0;
 printf("hello_world_c_add is coming Orz\n");
 printf("%d\n", a);
 printf("%d\n", b);
 sum = a+b;
 printf("sum=%d\n", sum);

 return sum;
}
int main(){
 printf("Hello World C :D");
 printf("sum=%d",hello_world_c_add(10,10));
 return 0;
}


3. 在php_foo.c裡面include hello_world_c.h檔


#include "hello_world_c.h"//內部的c func

#include "php_foo.h"

#if COMPILE_DL_FOO
ZEND_GET_MODULE(foo)
#endif

....

3. 新增一個PHP_FUNCTION: 呼叫剛剛的hello_world_c_add


//呼叫自定義的c函數,來處理加法

PHP_FUNCTION(foo_hello_add) {

  php_printf("run foo_hello_add\n");

  int val1;
  int val2;
  int sum;

  //parse parameters
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &val1,&val2 ) == FAILURE) {
      RETURN_FALSE;
  }

  php_printf("val1=%d\n",val1);
  php_printf("val2=%d\n",val2);

  sum = hello_world_c_add(val1,val2);

  RETURN_DOUBLE(sum);
}




範例: C實作/標頭檔搬到子資料夾




接著想把不同自定義的C函式庫分裝到不同的sub-folder後就爆了以下訊息:



目前這個範例卡關中...

範例: 全域變數的操作




範例: 回傳resouce



參考




  • https://github.com/jheth/hello-php-extension
  • 在 PHP Extension 中加入 static 和 dynamic library
  • Linux静态链接库与动态链接库的区别及动态库的创建
  • Linux中创建静态库和动态库
  • http://php.net/manual/en/internals2.structure.globals.php
  • https://github.com/walu/phpbook/blob/master/12.5.md


沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails