I wrote a Ruby plug-in with C + + swig in my early years, but in practice I wrote Ruby extensions in native C + + because it was fairly simple. But long useless or will forget, had to turn over the old code memories, write this blog, if the next time forget, also not to turn to the warehouse.
Establish EXTCONF.RB
Copy Code code as follows:
Require ' MKMF '
$libs = '-lstdc++ '
Create_makefile ' foo '
Establish foo.cc
Copy Code code as follows:
#include <ruby.h>
Value Plus (value self, value VA, value VB)
{
int a = Num2int (VA);
int b = Num2int (VB);
Return Int2num (A+B);
}
extern "C" void Init_foo ()
{
VALUE foo = rb_define_module ("foo");
Rb_define_module_function (foo, "Plus", Ruby_method_func (plus), 2);
}
Build extension foo.so
Copy Code code as follows:
$ Ruby Extconf.rb
$ make
# If you want to install to Site-ruby
$ make Site-install
test File Test.rb
Copy Code code as follows:
Require ' foo.so '
Puts Foo.plus (3,4)
$ Ruby Test.rb
7