Ruby中使用SWIG編寫ruby擴充模組執行個體_ruby專題

來源:互聯網
上載者:User

在使用ruby/rails的過程中,確實發現有時效能不盡人意,如產生一個擁有600項的item的3層樹形結構目錄要花去20ms,為提高效能在學慣用c/c++寫ruby模組的過程中,認識了swig,rubyInline等一系列協助編寫c/c++來提升ruby效能的協助工具輔助。

rubyInline用於內嵌c/c++程式,簡單快捷,swig則協助我們更容易地用c/c++寫出獨立的ruby模組。

swig的入門使用方法

目標:用swig/c++編寫一個ruby模組Test,並提供add方法作加法運算。

相關檔案:
(1).test.i 介面
(2).test.h 標頭檔
(3).test.cxx 函數實現
(4).extconf.rb 用於產生makefile
(5).(自動)test_wrap.cxx swig產生的test封裝
(6).(自動)Makefile Makefile檔案由ruby extconf.rb得到
(7).(自動)test.so ruby模組 由make得到

1、建立介面檔案test.i

複製代碼 代碼如下:

%module test
%{
//包含標頭檔
#include "test.h"
%}
//介面add
int add(int,int);

2、編寫wrap檔案
複製代碼 代碼如下:

swig -c++ -ruby test.i

得到test封裝檔案test_wrap.cxx

3、編寫test.h與test.cxx

複製代碼 代碼如下:

//test.h
#ifndef _TEST_TEST_H
#define _TEST_TEST_H
extern int add(int,int);
#endif
//test.cxx
#include "test.h"
int add(int left,int right)
{
        return left+right;
}

4、編寫extconf.rb用於快速產生makefile
複製代碼 代碼如下:

require 'mkmf'

dir_config 'test'
#stdc++庫,add函數未用到
$libs = append_library $libs,'stdc++'
create_makefile 'test'


運行 ruby extconf.rb 得到 Makefile 檔案

5、產生test模組

運行 make 得到模組 test.so

6、測試

複製代碼 代碼如下:

irb
irb(main):001:0> require 'test'
=> true
irb(main):002:0> Test.add 3,4
=> 7
irb(main):003:0> Test.add 3333333333333333333333,44444444444444444
TypeError: Expected argument 0 of type int, but got Bignum 3333333333333333333333
        in SWIG method 'add'
        from (irb):3:in `add'
        from (irb):3
        from :0
irb(main):004:0>

測試成功

7、swig

swig支援很多c++的進階特性來編寫ruby的模組,如類,繼承,重載,模板,stl等。

8、相關連結

(1).swig
(2).swig/ruby 文檔

9、備忘

本文的add函數過於簡單,對比ruby 3+4效能不升反降。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.