| « Install Rubygem in Ubuntu 8.10 | ruby脚本判断os » |
Introduction to write C extension for Ruby
Today, I am trying to use festival c/c++ api to say a word. After checking document, I decided to write an extension for ruby.
It is a simple task. All your need to do is:
Write a extension c file.
This file must define a function:
void Init_your_module_name()
It will be called on ruby loading it.
require "your_module_name"
In this function, generally, you must have following codes:
VALUE rb_mFestivalTTS;
rb_mFestivalTTS = rb_define_module( "FestivalTTS" ); //Define a module.
rb_define_module_function( rb_mFestivalTTS, "say", say, 1 ); //Define a function in module.
Write a extconf.rb
# extconf.rb
require 'mkmf'
dir_config('your_package_name')
create_makefile('your_package_name')
You can use find_library and find_header to add library and include path.
Run "make" command.
ruby extconf.rb
make
But it is a complex task too.
mkmf.rb doesn't support C
You must stick to C language.
You must be familiar with Ruby internal
All value passed bewteen extension and ruby inteperator is VALUE. It has a lot of api to manipuate VALUE. You must study <ruby.h>
Especially, you can use VALUE as a string by: StringValueCStr().