#includeclass TestClass
{
public:
TestClass(void){};
~TestClass(void){};
void SayHello(char* msg)
{
printf("Ruby C/C++ extention Example cdlz.
");
printf("Your Name is: %s
",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);
};