Chinaunix首页 | 论坛 | 博客
  • 博客访问: 235697
  • 博文数量: 21
  • 博客积分: 796
  • 博客等级: 军士长
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-16 01:03
文章分类
文章存档

2020年(1)

2017年(1)

2016年(1)

2015年(2)

2012年(9)

2011年(7)

我的朋友

分类: LINUX

2015-12-03 19:46:30


实验环境:CentOS 6.7


1. 安装Ruby
CentOS 6.7中默认安装的是Ruby 1.8,安装最新版2.2.3。

点击(此处)折叠或打开

  1. root [ ~ ]# wget
  2. root [ ~ ]# tar zxvf ruby-2.2.3.tar.gz
  3. root [ ~ ]# cd ruby-2.2.3
  4. root [ ~ ]# ./configure
  5. root [ ~ ]# make
  6. root [ ~ ]# make install

2. 安装SWIG

CentOS 6.7中默认安装的是SWIG 1.3,安装最新版3.0.7。需要先安装PCRE(Perl Compatible Regular Expressions)库。

点击(此处)折叠或打开

  1. root [ ~ ]# yum install pcre-devel
  2. root [ ~ ]# wget
  3. root [ ~ ]# tar zxvf swig-3.0.7.tar.gz
  4. root [ ~ ]# cd swig-3.0.7
  5. root [ ~ ]# ./configure
  6. root [ ~ ]# make
  7. root [ ~ ]# make install

3. 编写C语言函数库

点击(此处)折叠或打开

  1. /* File : example.c */

  2. double My_variable = 3.0;

  3. /* Compute factorial of n */
  4. int fact(int n) {
  5.   if (n <= 1) return 1;
  6.   else return n*fact(n-1);
  7. }

  8. /* Compute n mod m */
  9. int my_mod(int n, int m) {
  10.   return(n % m);
  11. }

4. 编写SWIG接口文件

点击(此处)折叠或打开

  1. /* File : example.i */
  2. %module example
  3. %{
  4.   /* Put headers and other declarations here */
  5.   extern double My_variable;
  6.   extern int fact(int);
  7.   extern int my_mod(int n, int m);
  8. %}

  9. extern double My_variable;
  10. extern int fact(int);
  11. extern int my_mod(int n, int m)

5. 生成C语言函数库的包装代码

点击(此处)折叠或打开

  1. root [ ~/example ]# swig -ruby example.i
此时生成example_wrap.c。

6. 编写extconf.rb文件

点击(此处)折叠或打开

  1. require 'mkmf'
  2. create_makefile('example')

7. 生成构建C函数库和包装代码

点击(此处)折叠或打开

  1. root [ ~/example ]# ruby extconf.rb
此时,生成Makefile,然后进行构建和安装

点击(此处)折叠或打开

  1. root [ ~/example ]# make
  2. root [ ~/example ]# make install
此时,生成共享库文件example.so。

8. 编写调用C函数库的Ruby程序

点击(此处)折叠或打开

  1. # file: run.rb
  2. require 'example'

  3. # Call a c function
  4. print "My_variable = ", Example.My_variable, "\n"
  5. print "fact(4) = ", Example.fact(4), "\n"
  6. print "my_mod(7, 2) = ", Example.my_mod(7, 2), "\n"
这里需要注意,Ruby模块的名称必须以大写字母开头,但特性的名称则应以小写字母开头。用户在为模块命名时可以用小写字母开头,构建生成的动态链接库的名称也会以小写字母开头。SWIG考虑到这种情况,将模块名称自动改为以大写字母开头。例如,在接口文件example.i中用“%module example”指令将模块命名为example,构建生成的动态链接库名为example.so。在Ruby代码中,用“require 'example'”加载特性example,即加载example.so,但在引用模块名称时应使用Example。

9. 执行Ruby程序调用C函数库

点击(此处)折叠或打开

  1. root [ ~/example ]# ruby run.rb
  2. My_variable = 3.0
  3. fact(4) = 24
  4. my_mod(7, 2) = 1

阅读(5101) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~