终于把一切都准备好了。现在就可以开始 把ruby往c++里丢了。
那么,首先;
//============================================================================
// Name : RubyCPP.cpp
// Author : frodo
//============================================================================
#include <iostream>
#include <ruby.h>
using namespace std;
VALUE rb_ext_p(VALUE thiz, VALUE obj){
VALUE str = rb_obj_as_string(rb_inspect(obj));
const char* cStr = StringValueCStr(str);
if(cStr){
printf("%s \n", cStr);
}
return 0;
}
void initExtKreal(){
rb_define_module_function(rb_mKernel, "p", RUBY_METHOD_FUNC(rb_ext_p), -2);
}
int main() {
ruby_init();
ruby_init_loadpath();
ruby_script("ruby-android");
initExtKreal();
rb_eval_string("p '122', 'xxx'");
rb_eval_string("p '2'");
rb_eval_string("p '3'");
rb_eval_string("p '4'");
return 0;
}
理论来讲, p 函数就应该是被重定义,并且 运行 脚本 p '122' 的时候能进入我的回调。
主要讲一下
rb_define_module_function
这个函数,这个函数还有对应的几个兄弟。
void rb_define_method(VALUE,const char*,VALUE(*)(ANYARGS),int);
void rb_define_module_function(VALUE,const char*,VALUE(*)(ANYARGS),int);
void rb_define_global_function(const char*,VALUE(*)(ANYARGS),int);
分别是 对应定义 类的方法(class),模块的方法 (module) 和(全局的方法。。=皿= ruby有全局函数的么。。OTZ)global
参数分别为
- 对象(分别是想定义在哪)
- 方法名
- 方法对应的函数指针,可直接RUBY_METHOD_FUNC宏
- 关键的就是最后一个参数了。
分几种
-2, -1, 0, 1, 2.3...15
-2 是变长参数
函数原型为
VALUE rb_method(VALUE thiz, VALUE ary)
-1 是依然是变参数,不过就不是数组了
函数原型为
VALUE rb_method(int argc, VALUE* argv, VALUE thiz)
0 是 无参数
VALUE rb_method(VALUE thiz);
1 开始,就是参数数量了
函数原型要对应的加上。
最多到15。= =什么方法会用到这么多啊