I am writing a sample C Ruby extension which needs a C character to Ruby string conversion.
I have created extconf.rb and a file called x.c.
extconf.rb:
require 'mkmf'
create_makefile 'x'
x.c:
#include "ruby.h"
void Init_x() {
char c = 'b' ;
VALUE b = rb_str_new_cstr(c) ;
rb_gv_set("$a", b) ;
rb_global_variable(&b) ;
}
rb_str_new_cstr() expects a C string, not a character. When I compile and run this code, I get segmentation fault, and Ruby crashes.
I can do this instead, which works just fine:
#include "ruby.h"
void Init_x() {
char *c = "b" ;
VALUE b = rb_str_new_cstr(c) ;
rb_gv_set("$a", b) ;
rb_global_variable(&b) ;
}
But the problem is if I have something like fscanf(file, "%c", &char)
which sets char
to a character, I have to convert it to a string first and change %c
to %1s
, which sounds like a bit slower approach.
Is there a way to directly convert a C character into a Ruby string?