Ruby uses C + + extension instances (with C + + extended code sample) _ruby topics

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.