æ¡å¼µã©ã¤ãã©ãªãã¥ã¼ããªã¢ã«ããã£ã¦ã¿ã#2
ç¶ãï¼
æ°å¤ã®ããã¨ã
æ´æ°ã®å ç®ããã£ã¦ã¿ãï¼
å¦çå®ä½
- add.c
int add(a, b) int a, b; { return(a + b); }
int ã 2 ã¤åãåã£ã¦å ç®ããçµæã int ã§è¿ãï¼ã³ã¼ãã«åé¡ãªãããã¡ãã£ã¨ãã¹ãã®ããã«å®è¡ãã¦ã¿ã
- main.c
#include <stdio.h> int add(int a, int b); int main() { int a, b; a = 1; b = 2; printf("%d + %d = %d\n", a, b, add(a, b)); }
% cc -o add add.c main.c % ./add 1 + 2 = 3
ã¾ãæ®éã«å®è¡ãããï¼
C 㨠Ruby ã®æ¥ç¶
Ruby ã§ã¯æ°å¤ã§ãããªãã¸ã§ã¯ããªã®ã§ï¼ C ã® int åã«å¤æããå¿ è¦ãããï¼ããããã£ã¦ãããã®ãï¼ä»¥ä¸ã®ãã¯ãã»é¢æ°ãããï¼
- FIX2INT
- Ruby ãªãã¸ã§ã¯ãã int åã¸å¤æãã
- NUM2INT
- Numeric ãã©ããããã§ãã¯ãã¦ãã int åã¸ã¨å¤æããï¼Numeric ã§ãªãå ´åã¯ä¾å¤ãåãï¼
- INT2FIX
- signed int(31bit) ã Ruby ã® Fixnum ã¸ã¨å¤æããï¼
- INT2NUM
- int ã Ruby ã® Interger ã¸å¤æããï¼æ¡ããµãã®å ´å㯠Bignum ã¸ã¨èªåæ¡å¼µãã¦å¤æããï¼
- NUM2DBL
- Numeric ãã©ããããã§ãã¯ãã¦ãã double åã¸ã¨å¤æããï¼Numeric ã§ãªãå ´åã¯ä¾å¤ãåãï¼
- rb_float_new(float)
- float/double åã®å®æ°ã Float åã¸ã¨å¤æããï¼
ããã¦ããã使ã£ã¦ã©ããã¼ãä½ãï¼
- test2.c
#include "ruby.h" int add(int a, int b); VALUE wrap_add(self, aa, bb) VALUE self, aa, bb; { int a, b, result; a = FIX2INT(aa); // FIX2INT ã«ãã£ã¦ï¼VALUE åæ§é ä½ã int åã¸å¤æãã b = FIX2INT(bb); // åä¸ result = add(a, b); return INT2FIX(result); // INT2FIX ã«ãã£ã¦ï¼int åã VALUE åæ§é ä½ã¸å¤æãã } void Init_test() { VALUE module; module = rb_define_module("Test"); // Test ã¢ã¸ã¥ã¼ã«ãçæãã rb_define_module_function(module, "add", wrap_add, 2); // module(Test ã¢ã¸ã¥ã¼ã«) ã« add ã¡ã½ãããï¼å¼æ°ã®æ°ã2ã¨ãã¦ç»é²ãã }
å¦çã®æµã
åºæ¬çã«前回ã¨ä¸ç·ï¼ãã¨ãªãã®ã¯ä¸è¨ã®ãã¯ã使ã£ã¦ C ã®å㨠Ruby ãªãã¸ã§ã¯ããç¸äºå¤æãã¦ãããã¨ï¼
ã³ã³ãã¤ã«ãã¦å®è¡ãã
extconf.rb ã¯ååã¨åãã®ã使ãï¼
- extconf.rb
require 'mkmf' create_makefile('test')
% ruby extconf.rb % make % ruby -r'test' -e'puts Test.add(1,2)' 3
Ruby ãªãã¸ã§ã¯ã㨠C ã®åã®ç¸äºå¤æç¨ã®ãã¯ããªãé¢æ°ãªããããã®ã§ï¼ããã使ãã°æ¥ç¶ã«ã¯ããã»ã©è¦å´ããªãå°è±¡ï¼