"Leon, Reloaded". 这是我的心情,欢迎跟你分享。

星期日, 九月 03, 2006

Quickly Create a Ruby extension by SWIG

OK, here we go.
First, createing a example.c of the module. This module is the implementation of your module.
--------------------------------------------------------------------
/* File : example.c */

#include
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);
}
--------------------------------------------------------------------
And then, we should define the interface of this module. --------------------------------------------------------------------
/* 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();
--------------------------------------------------------------------
OK. Here we go. We will "cook" it, now. :) -------------------
$ swig -c++ -ruby example.i
-------------------
After this, it will create the "wraper" layer of this extension, example_wrap.cxx. --------------------------------------------------------------------
$ swig -c++ -ruby example.i
$ g++ -c example.cxx
$ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.8/i686-linux
$ g++ -shared example.o example_wrap.o -o example.so --------------------------------------------------------------------
OK. we got it. :) Now, we would start the Ruby interactive shell to test it. --------------------------------------------------------------------
leon@localhost ~/ruby/swig
$ irb irb(main):001:0> require 'example'
=> true
irb(main):002:0> Example.fact(4)
=> 24
irb(main):003:0> Example.My_variable
=> 3.0
irb(main):004:0> Example.get_time
=> "Sun Sep 3 13:26:47 2006\n"
--------------------------------------------------------------------

OK. if you want more information, please reference this link : SWIG and Ruby.

0 Comments:

发表评论

<< Home