Skip to content

Instantly share code, notes, and snippets.

@ryanb
Created September 19, 2008 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanb/11611 to your computer and use it in GitHub Desktop.
Save ryanb/11611 to your computer and use it in GitHub Desktop.
/*
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