Skip to content

Instantly share code, notes, and snippets.

@adamhunter
Created February 26, 2013 19:00
Show Gist options
  • Save adamhunter/5041075 to your computer and use it in GitHub Desktop.
Save adamhunter/5041075 to your computer and use it in GitHub Desktop.
A Ruby extension that will allow access to instance variables that are set in C and do not begin with an "@".
require 'mkmf'
have_header('ruby.h') or missing('ruby.h')
dir_config("ivar")
create_makefile("ivar")
ruby extconf.rb && make && irb -I . -r ivar
#include "ruby.h"
static VALUE rb_mIvar;
static VALUE rb_ivar_iv_get(VALUE self, VALUE key) {
return rb_ivar_get(self, rb_to_id(key));
}
static VALUE rb_ivar_iv_set(VALUE self, VALUE key, VALUE value) {
return rb_ivar_set(self, rb_to_id(key), value);
}
void Init_ivar() {
rb_mIvar = rb_define_module("Ivar");
rb_define_method(rb_mIvar, "ivar_get", rb_ivar_iv_get, 1);
rb_define_method(rb_mIvar, "ivar_set", rb_ivar_iv_set, 2);
}
$:.unshift('.')
require 'ivar'
Object.send(:include, Ivar)
e = StandardError.new("foo")
puts "Error message is: #{e.message}"
e.ivar_set(:mesg, "bar")
puts "Error message is: #{e.message}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment