Making The Road Blog

http://makingx.net/blog/

mtr2.0
Making The Road はmakingのお勉強用サイトです.PHP, Javascriptを中心にいろいろ試してoutputしていきたい.
当サイトの訪問者は24時間以内にこんな単語↓で検索されています (マウスオーバーすると単語を含むqueryを表示します!)

さくらでSWIG

PHPのエクステンションをPecl_Codegenで書くのもいいけど,めんどくさくなってきた.
よくCのライブラリにはPython用のインターフェイスが用意されていたりするが,どうもあれはSWIGというソフトでCから自動生成しているみたい.
みてみるとPHPでも使えるみたいなのでやってみた.

SWIGインストール

いつものやつ

wget http://prdownloads.sourceforge.net/swig/swig-1.3.33.tar.gz
tar xzvf swig-1.3.33.tar.gz
cd swig-1.3.33
./configure --prefix=$HOME/usr
make
make install

Example

公式サイトにのってるやつ

example.c

#include <time .h>
double My_variable = 3.0;
 
int fact(int n) {
  if (n < = 1) return 1;
  else return n*fact(n-1);
}
 
int my_mod(int x, int y) {
  return (x%y);
}
 
char *get_time()
{
  time_t ltime;
  time(&ltime);
  return ctime(&ltime);
}

example.i

 /* example.i */
 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}
 
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

PHPラッパー生成

今回はPHP5用.PHP4もある

swig -php5 example.i
gcc -c example.c example_wrap.c `php-config --includes` -fPIC
gcc -shared example_wrap.o example.o -o example.so
mv example.so `php-config --extension-dir`
php -r 'dl("example.so"); var_dump(My_variable_get(), fact(5), my_mod(7, 3), get_time());'

結果は

float(3)
int(120)
int(1)
string(25) "Sat Jan  5 02:14:31 2008
"

できたーー!
PHP用は機能がイマイチらしいのでちょっと使ってみてどんなもんか調べてみます!

参考リンク

カテゴリー: Sakura, PECL, PHP, C | コメント( 0 ) | 2008/01/05 02:05:24 by making
ソーシャルブックマーク: add to hatena hatena.comment (1) add to del.icio.us (1) add to livedoor.clip (0) add to Yahoo!Bookmark (0) Total: 2
トラックバックURL:

Leave a Reply

求人