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

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

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值