ryanb (owner)

Revisions

gist: 11611 Download_button fork
public
Public Clone URL: git://gist.github.com/11611.git
Embed All Files: show embed
hello.c #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
PROBLEM:
>> h = Hello.new('hi!')
=> #<Hello:0x4b730>
>> h.greet
hi!=> nil
>> h.greet
hi!=> nil
..
>> h.greet
hi!=> nil
>> h.greet
=> nil
>> h.greet
=> nil
*/
 
#include <ruby.h>
 
VALUE cHello;
 
#define HELLO(obj) (Check_Type(obj, T_DATA), (struct Hello*)DATA_PTR(obj))
 
struct Hello {
  char *greeting;
};
 
static void hello_free(struct Hello *hello)
{
  free(hello->greeting);
}
 
static void hello_mark(struct Hello *hello)
{
}
 
static VALUE hello_new(VALUE klass)
{
  struct Hello *hello;
  return Data_Make_Struct(klass, struct Hello, hello_mark, hello_free, hello);
}
 
static VALUE hello_init(VALUE obj, VALUE greeting)
{
  HELLO(obj)->greeting = RSTRING(greeting)->ptr;
  return Qnil;
}
 
static VALUE hello_greet(VALUE obj)
{
  printf(HELLO(obj)->greeting);
  return Qnil;
}
 
void Init_hello()
{
  cHello = rb_define_class("Hello", rb_cObject);
  rb_define_alloc_func(cHello, hello_new);
  rb_define_method(cHello, "initialize", hello_init, 1);
  rb_define_method(cHello, "greet", hello_greet, 0);
}