Ruby使用C/C++扩展,可以让ruby变得很强大。 #include<stdio.h> #include<ruby.h> class TestClass { public: TestClass(void){}; ~TestClass(void){}; void SayHello(char* msg) { printf("Ruby C/C++ extention Example cdlz.\n"); printf("Your Name is: %s\n",msg); } }; //VALUE self这个是不变的。指向自己。 第二个: VALUE name则是我们这个函数需要的参数。 VALUE method_sayhello(VALUE self,VALUE name){ long length=0; char* yourname = rb_str2cstr(name, &length); //rb_str2cstr,转换到C语言的字符串 TestClass* test=new TestClass(); test->SayHello(yourname); delete test; return rb_str_new2(yourname); //rb_str_new2,由C语言的字符串转换为Ruby的String。 }; VALUE method_cfunction(VALUE self, VALUE va, VALUE vb) { int a = NUM2INT(va); int b = NUM2INT(vb); return INT2NUM(a+b); } VALUE hellotest = Qnil; //Qnil 即为 NULL /* 如果全部都是C的,则需要加上extern "C" void Init_HelloTest() */ void Init_HelloTest(){ hellotest = rb_define_module("HelloTest"); //定义一个ruby方法,在ruby中调用。最后一个参数为 ruby方法的参数个数 rb_define_method(hellotest, "sayhello", RUBY_METHOD_FUNC(method_sayhello), 1); rb_define_method(hellotest, "cfunction_plus", RUBY_METHOD_FUNC(method_cfunction), 2); }; 上述代码,实现了两个ruby方法:sayhello和cfunction_plus 2. extconf.rb require 'mkmf' extension_name = "HelloTest" dirbase="D:/ruby/vc" ruby_lib_base= dirbase+"/lib" ruby_include_base= dirbase+"/include" dir_config(extension_name) #如果是windows则取消下面注释,注意,目录名称不能有空格 #dir_config(extension_name,ruby_include_base,ruby_lib_base) create_makefile(extension_name) 之后运行 ruby extconf.rb,以便生成Makefile文件。 linux下,一般直接运行make即可生成so,然后make install 即可。 ruby extconf.rb nmake clean nmake mt -manifest %1.so.manifest -outputresource:%1.so;2 nmake install 如果没有错误,编译通过,windows下可以使用如下命令查看dll导出函数情况: require "HelloTest" include HelloTest puts HelloTest.sayhello("aaa") puts HelloTest.cfunction_plus(111,222) puts HelloTest.methods - Object.methods 注意:如果是在扩展中有输出,则只有在ruby的输出全部打印完毕后,才会有扩展中的输出(直接使用ruby test.rb,顺序有正常。。。暂时无解。。。)。
|
|