8

我正在编写一个 Ruby 扩展并使用该函数Data_wrap_struct

为了参与 Ruby 的标记和清除垃圾收集过程,我需要定义一个例程来释放我的结构,以及一个例程来标记从我的结构到其他结构的任何引用。我通过经典free函数来释放内存,但我不知道如何使用标记函数。

我的结构听起来像这样

typedef struct
{
  int x;
  int y;
} A;

typedef struct
{
  A collection[10];
  int current;
} B;

我认为我需要一个标记函数来标记collection结构 B中的引用。

有人可以给我看一个例子来看看标记功能是如何工作的?

4

1 回答 1

6

mark 函数用于标记 C 结构拥有的任何Ruby 对象

typedef struct {
    VALUE ruby_object;
} MyStruct;

void mark(void * p) {
    /* p is the wrapped pointer to the MyStruct instance */
    MyStruct * my_struct = (MyStruct *) p;
    rb_gc_mark(my_struct->ruby_object);
}

如果你的结构拥有的对象没有被标记,垃圾收集器可能会清理它,你的代码最终可能会尝试使用一个最终对象。

于 2012-02-24T17:08:04.570 回答