Ruby Binding

In C binding looks like this:

// GetBindingPtr(bindval, bind) -> bind = rb_binding_t
typedef struct {
VALUE env; // GetEnvPtr(envval, env) -> env = rb_env_t
VALUE path;
unsigned short first_lineno;
} rb_binding_t;

typedef struct {
VALUE *env; // memory
int env_size;
int local_size;
VALUE prev_envval; /* for GC mark */
rb_block_t block;
} rb_env_t;

typedef struct rb_block_struct {
VALUE self; /* share with method frame if it’s only block */
VALUE *ep; /* share with method frame if it’s only block */
rb_iseq_t *iseq; // instruction sequence
VALUE proc;
} rb_block_t;

The interesting part is environment (I made some comments about it):

envval = env_alloc();
GetEnvPtr(envval, env);
env->env_size = local_size + 1 + 1;
env->local_size = local_size;
env->prev_envval = penvval;
env->env = ALLOC_N(VALUE, env->env_size);
/* env->env looks like this (2 local variables in this case)
mem 0000 setlocal 3
mem 0008 setlocal 2
mem 0010 RubyVM::Env object, previous "frame self" – not 100% about this one <– cfp->ep points here
mem 0018 RubyVM::Env object, "frame self" (= envval)

And how to eval on binding from C (assuming you have binding object only in C)?
VALUE bind_eval_c(VALUE self, VALUE bindval, const char *eval_str, const char *vfile, const int vline) {
VALUE args[4];
args[0] = rb_str_new2(eval_str); // eval string
args[1] = bindval; // VALUE object with class Binding
args[2] = rb_str_new2(vfile); // what you want ruby to think ruby file is
args[3] = LL2NUM(vline); // what you want ruby to think line number is
//rb_f_eval(4, args, self);
return rb_funcall(self, rb_intern("eval"), 4, args[0], args[1], args[2], args[3]);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s