实验环境:CentOS 6.7
1. 安装Ruby
CentOS 6.7中默认安装的是Ruby 1.8,安装最新版2.2.3。
点击(此处)折叠或打开
- root [ ~ ]# wget
- root [ ~ ]# tar zxvf ruby-2.2.3.tar.gz
- root [ ~ ]# cd ruby-2.2.3
- root [ ~ ]# ./configure
- root [ ~ ]# make
- root [ ~ ]# make install
2. 安装SWIG
CentOS 6.7中默认安装的是SWIG 1.3,安装最新版3.0.7。需要先安装PCRE(Perl Compatible Regular Expressions)库。
点击(此处)折叠或打开
- root [ ~ ]# yum install pcre-devel
- root [ ~ ]# wget
- root [ ~ ]# tar zxvf swig-3.0.7.tar.gz
- root [ ~ ]# cd swig-3.0.7
-
root [ ~ ]# ./configure
- root [ ~ ]# make
- root [ ~ ]# make install
3. 编写C语言函数库
点击(此处)折叠或打开
-
/* File : example.c */
-
-
double My_variable = 3.0;
-
-
/* Compute factorial of n */
-
int fact(int n) {
-
if (n <= 1) return 1;
-
else return n*fact(n-1);
-
}
-
-
/* Compute n mod m */
-
int my_mod(int n, int m) {
-
return(n % m);
- }
4. 编写SWIG接口文件
点击(此处)折叠或打开
-
/* File : example.i */
-
%module example
-
%{
-
/* Put headers and other declarations here */
-
extern double My_variable;
-
extern int fact(int);
-
extern int my_mod(int n, int m);
-
%}
-
-
extern double My_variable;
-
extern int fact(int);
- extern int my_mod(int n, int m)
5. 生成C语言函数库的包装代码
点击(此处)折叠或打开
- root [ ~/example ]# swig -ruby example.i
6. 编写extconf.rb文件
点击(此处)折叠或打开
- require 'mkmf'
- create_makefile('example')
7. 生成构建C函数库和包装代码
点击(此处)折叠或打开
- root [ ~/example ]# ruby extconf.rb
点击(此处)折叠或打开
- root [ ~/example ]# make
- root [ ~/example ]# make install
8. 编写调用C函数库的Ruby程序
点击(此处)折叠或打开
- # file: run.rb
- require 'example'
-
- # Call a c function
- print "My_variable = ", Example.My_variable, "\n"
- print "fact(4) = ", Example.fact(4), "\n"
- print "my_mod(7, 2) = ", Example.my_mod(7, 2), "\n"
9. 执行Ruby程序调用C函数库
点击(此处)折叠或打开
- root [ ~/example ]# ruby run.rb
- My_variable = 3.0
- fact(4) = 24
- my_mod(7, 2) = 1