mrubybind automatically creates C function/class-method binder for mruby, using C++ template partial specialization.
- Put following source codes into your project.
- mrubybind.cc
- mrubybind.h
- Include "mrubybind.h"
- Use
MrubyBind
instance to bind C function/class-method to mruby.
- C function (Any type you want):
int square(int x) {
return x * x;
}
- Bind it using mrubybind
bind
method:
#include "mrubybind.h"
void install_square_function(mrb_state* mrb) {
mrubybind::MrubyBind b(mrb);
b.bind("square", square);
}
You can throw away MrubyBind
instance after binding function.
- Call it from mruby:
puts square(1111) #=> 1234321
- C++ class:
class Foo {
public:
Foo(int x) : x_(x) {
cout << "Foo::ctor(" << x << ")" << endl;
}
virtual ~Foo() {
cout << "Foo::dtor()" << endl;
}
int bar(int y) {
return x_ + y;
}
static int baz(int z) {
return z * z;
}
private:
int x_;
};
- Bind C++ class using mrubybind
bind_class
,bind_instance_method
andbind_static_method
method:
#include "mrubybind.h"
// Helper function for constructor.
Foo* new_foo(int x) {
return new Foo(x);
}
void install_foo_class(mrb_state* mrb) {
mrubybind::MrubyBind b(mrb);
b.bind_class("Foo", new_foo);
b.bind_instance_method("Foo", "bar", &Foo::bar);
b.bind_static_method("Foo", "baz", &Foo::baz);
}
- Call it from mruby:
foo = Foo.new(123) #=> Foo::ctor(123)
p foo #=> #<Foo:0x7fa828803d80>
p foo.bar(567) #=> 690
p Foo.baz(9999) #=> 99980001
#=> Foo::dtor()
- Pass
RClass*
instace forMrubyBind
constructor:
void install(mrb_state* mrb) {
RClass* mod = mrb_define_module(mrb, "YourModule");
mrubybind::MrubyBind b(mrb, mod);
b.bind("foo", foo);
}
You can use YourModule.foo
function from mruby.
- Use
bind_const
method:
void install(mrb_state* mrb) {
mrubybind::MrubyBind b(mrb);
b.bind_const("FOO", FOO_VALUE);
}
C type | mruby type |
---|---|
int, unsigned int | Fixnum |
float, double | Float |
const char*, string | String |
bool | TrueClass or FalseClass |
void* | Object |
See mrubybind.h.
MIT license.