Search code examples
cmruby

How to pass a C string to a Ruby method using mruby?


I am getting started with C and mruby. I have a program that calls to a Ruby function using the mruby mrb_load_string function. I want to pass the argument from the C function to the Ruby function. How can I achieve this?

void on_key(const char *key) {
  mrb_load_string(mrb, "input_received()"); // how do I pass key as an argument?
}

Solution

  • If your ruby function takes a string as a parameter input, then:

    void on_key(const char *key) {
      char arg[64];
      sprintf(arg,"input_received(\"%s\")",key);//Embed key as an argument to the function
      mrb_load_string(mrb, arg); 
    }
    

    should do what you wanted.