1

How can I convert a C++ std::string object into a Ruby VALUE object?

I tried rb_str_new2(c_string), but it did not work.

I have a function

VALUE foo(){return rb_str_new2(c_string);};

and that gives an error message:

cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’
sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

4

You are passing std::string to the function, but it expects a null-terminated const char *.

The std::string::c_str() member function can be used to get one:

rb_str_new_cstr(string.c_str());
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
  • What's the difference between this and `rb_str_new2`? Can't find much intel about `rb_str_new_cstr` – Niklas B. Apr 18 '12 at 15:39
  • @NiklasB, [they are the same function](https://github.com/ruby/ruby/blob/trunk/README.EXT#L179). I prefer `rb_str_new_cstr` because I can infer that the function takes a C string as parameter. – Matheus Moreira Apr 18 '12 at 15:43
  • 1
    Yes, I thought it might just be a more descriptive alias. Thanks, good to know, will use this in the future :) – Niklas B. Apr 18 '12 at 15:45
  • 1
    @MatheusMoreira Ruby strings and C++ strings can contain zeros. So I would suggest rb_str_new( string.data(), string.size() ) – Torsten Robitzki Jul 16 '12 at 17:09