1
我只想讓C擴展類的一個實例生成,所以我想包含單例模塊。使用Singleton的Ruby C擴展
void Init_mousetest() {
VALUE mouseclass = rb_define_class("MyMouse",rb_cObject);
rb_require("singleton");
VALUE singletonmodule = rb_const_get(rb_cObject,rb_intern("Singleton"));
rb_include_module(mouseclass,singletonmodule);
rb_funcall(singletonmodule,rb_intern("included"),1,mouseclass);
###^Why do I need this line here?
rb_define_method(mouseclass,"run",method_run,0);
rb_define_method(mouseclass,"spawn",method_spawn,0);
rb_define_method(mouseclass,"stop",method_stop,0);
}
據我瞭解,這是什麼線做的是一樣的Singleton.included(MyMouse)
,但如果我嘗試調用的是,我得到
irb(main):006:0> Singleton.included(MyMouse)
NoMethodError: private method `included' called for Singleton:Module
from (irb):6
from C:/Ruby19/bin/irb:12:in `<main>'
爲什麼rb_include_module
行爲不同於我期望它?此外任何切線的討論/解釋或相關文章,讚賞。 Ruby初學者在這裏。
此外,它似乎我可以保持我的擴展儘可能簡單,只是稍後破解某種接口,以確保我只允許一個實例。或者只是將我的鼠標相關的方法放入一個模塊中...任何一種都有意義?