ruby windows linux,Ruby使用C/C++扩展(包括windows和linux)

这篇博客介绍了如何使用C++实现Ruby扩展,包括创建`TestClass`类,定义`SayHello`方法,以及在C++中处理Ruby的字符串。通过`rb_str2cstr`将Ruby字符串转换为C++字符串,调用C++方法,然后用`rb_str_new2`将结果转回Ruby的String。此外,还展示了如何在Ruby中定义和调用`cfunction_plus`方法进行简单的加法操作。
摘要由CSDN通过智能技术生成

#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);

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值