Ruby使用C/C++擴(kuò)展,可以讓ruby變得很強(qiáng)大。 #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則是我們這個函數(shù)需要的參數(shù)。 VALUE method_sayhello(VALUE self,VALUE name){ long length=0; char* yourname = rb_str2cstr(name, &length); //rb_str2cstr,轉(zhuǎn)換到C語言的字符串 TestClass* test=new TestClass(); test->SayHello(yourname); delete test; return rb_str_new2(yourname); //rb_str_new2,由C語言的字符串轉(zhuǎn)換為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中調(diào)用。最后一個參數(shù)為 ruby方法的參數(shù)個數(shù) rb_define_method(hellotest, "sayhello", RUBY_METHOD_FUNC(method_sayhello), 1); rb_define_method(hellotest, "cfunction_plus", RUBY_METHOD_FUNC(method_cfunction), 2); }; 上述代碼,實(shí)現(xiàn)了兩個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) 之后運(yùn)行 ruby extconf.rb,以便生成Makefile文件。 linux下,一般直接運(yùn)行make即可生成so,然后make install 即可。 ruby extconf.rb nmake clean nmake mt -manifest %1.so.manifest -outputresource:%1.so;2 nmake install 如果沒有錯誤,編譯通過,windows下可以使用如下命令查看dll導(dǎo)出函數(shù)情況: require "HelloTest" include HelloTest puts HelloTest.sayhello("aaa") puts HelloTest.cfunction_plus(111,222) puts HelloTest.methods - Object.methods 注意:如果是在擴(kuò)展中有輸出,則只有在ruby的輸出全部打印完畢后,才會有擴(kuò)展中的輸出(直接使用ruby test.rb,順序有正常。。。暫時無解。。。)。
|
|