| 赞 | 72 |
| VIP | |
| 好人卡 | |
| 积分 | 23 |
| 经验 | |
| 最后登录 | 2022-3-9 |
| 在线时间 | 4033 小时 |
…あたしは天
- 梦石
- 0
- 星屑
- 2308
- 在线时间
- 4033 小时
- 注册时间
- 2010-10-4
- 回帖
- 10548
 
|
发表于 2015-8-6 18:57:31
|
显示全部楼层
本帖最后由 taroxd 于 2015-8-6 19:47 编辑
寒冷魔王 发表于 2015-8-6 12:02 
楼上的都太难了,顺便围观状元卖萌
好吧,就问一个简单的问题
送你个不管越界不检查参数的无责任数组(比原生Ruby Array慢,我会乱说?):
[pre lang="C" file="my_array.c"]#include <ruby.h>
struct my_array {
size_t size;
VALUE *ptr;
};
static void
my_array_free(void *p) {
struct my_array *ptr = p;
if (ptr->size > 0)
free(ptr->ptr);
}
static VALUE
my_array_alloc(VALUE klass) {
VALUE obj;
struct my_array *ptr;
obj = Data_Make_Struct(klass, struct my_array, NULL, my_array_free, ptr);
ptr->size = 0;
ptr->ptr = NULL;
return obj;
}
static VALUE
my_array_init(VALUE self, VALUE size) {
struct my_array *ptr;
size_t requested = NUM2SIZET(size);
Data_Get_Struct(self, struct my_array, ptr);
ptr->ptr = (VALUE *)malloc(requested * sizeof(VALUE));
ptr->size = requested;
return self;
}
static VALUE
my_array_size(VALUE self) {
struct my_array *ptr;
Data_Get_Struct(self, struct my_array, ptr);
return SIZET2NUM(ptr->size);
}
static VALUE
my_array_get(VALUE self, VALUE index) {
struct my_array *ptr;
Data_Get_Struct(self, struct my_array, ptr);
return (ptr->ptr)[NUM2LONG(index)];
}
static VALUE
my_array_set(VALUE self, VALUE index, VALUE value) {
struct my_array *ptr;
Data_Get_Struct(self, struct my_array, ptr);
(ptr->ptr)[NUM2LONG(index)] = value;
return value;
}
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport)
void
Init_my_array(void) {
VALUE cMyArray;
cMyArray = rb_const_get(rb_cObject, rb_intern("MyArray"));
rb_define_alloc_func(cMyArray, my_array_alloc);
rb_define_method(cMyArray, "initialize", my_array_init, 1);
rb_define_method(cMyArray, "size", my_array_size, 0);
rb_define_method(cMyArray, "[]", my_array_get, 1);
rb_define_method(cMyArray, "[]=", my_array_set, 2);
}
#ifdef __cplusplus
}
#endif
[/pre]
[pre lang="ruby"]class MyArray; end
require_relative 'my_array'
a = MyArray.new(2)
a[0] = 1
p a[0][/pre] |
评分
-
查看全部评分
|