swig を使う
Python, Perl, Tcl などのスクリプト言語から
C の関数を簡単に呼び出せるようにするツール。
C による関数を Python で呼び出す例
C 言語で shared library (.sl) を作り、Python から呼び出します。
HP の gcc は shared library をうまく作れないので、
cc でコンパイルします。
example.c
/* File : 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(<ime);
return ctime(<ime);
}
/* end of file */
example.i
/* example.i */
%module example
%{
/* Put header files here (optional) */
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
実行例
% swig -python example.i
% cc -Aa +z -c example.c example_wrap.c \
-I/usr/local/include/python1.4 -I/usr/local/lib/python1.4/config
% ld -b example.o example_wrap.o -o example.sl
% python
Python 1.4 (Nov 7 1997) [GCC 2.7.2]
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import example
>>> example.fact(5)
120
>>> example.my_mod(7,3)
1
>>> example.get_time()
'Fri Nov 7 21:43:32 1997\012'
>>>
C による関数を Perl5 で呼び出す例
HP では shared library による方法がうまく行きません。
しかしこのような場合にも C による関数を組み込んで、
新たな Perl5 処理系を作る、という方法が使えます。
% swig -static -perl5 -lperlmain.i example.i
% gcc -o a.out example.c example_wrap.c \
/opt/perl5/lib/PA-RISC1.1/5.003/CORE/libperl.a -lm \
-I/opt/perl5/lib/PA-RISC1.1/5.003/CORE
% ./a.out
use example;
print $example::My_variable,"\n";
print example::fact(5),"\n";
print example::get_time(),"\n";
<ctrl-d>
3
120
Mon Nov 10 17:04:05 1997
Takuya NISHIMOTO
Last modified: Mon Nov 10 19:49:09 1997