Created
September 19, 2008 15:42
-
-
Save ryanb/11611 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment