単純なRuby拡張を作った

とりあえず、簡単なのはさくっとできた。

rua.c (MSC)

__declspec(dllexport) void Init_rua(void);

#include "ruby.h"

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

struct rua {
  lua_State *L;
};

static void rua_free(struct rua *p) {
  if (p->L) {
    lua_close(p->L);
  }

  free(p);
}

static VALUE rua_alloc(VALUE klass) {
  struct rua *p = ALLOC(struct rua);
  return Data_Wrap_Struct(klass, 0, rua_free, p);
}

static VALUE rua_initialize(VALUE self) {
  struct rua *p;
  Data_Get_Struct(self, struct rua, p);

  p->L = lua_open();
  luaL_openlibs(p->L);

  return Qnil;
}

static VALUE rua_eval(VALUE self, VALUE str) {
  struct rua *p;
  Data_Get_Struct(self, struct rua, p);

  luaL_loadstring(p->L, STR2CSTR(str));
  lua_pcall(p->L, 0, 0, 0);

  return self;
}

void Init_rua(void)
{
  VALUE Rua;

  Rua = rb_define_class("Rua", rb_cObject);
  rb_define_alloc_func(Rua, rua_alloc);
  rb_define_private_method(Rua, "initialize", rua_initialize, 0);
  rb_define_method(Rua, "eval", rua_eval, 1);
}

Rubyのコード

require 'rua'

rua = Rua.new

rua.eval <<EOS
  print(100)
EOS


100