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*)’
3
  • 1
    How did it not work? What's your code? Commented Apr 18, 2012 at 15:27
  • 3
    rb_str_new2(string_object.c_str()); should do the job easy. Commented Apr 18, 2012 at 15:34
  • 2
    Why do you call your variable c_string, if it's not a C string? oO Commented Apr 18, 2012 at 15:53

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

4 Comments

What's the difference between this and rb_str_new2? Can't find much intel about rb_str_new_cstr
@NiklasB, they are the same function. I prefer rb_str_new_cstr because I can infer that the function takes a C string as parameter.
Yes, I thought it might just be a more descriptive alias. Thanks, good to know, will use this in the future :)
@MatheusMoreira Ruby strings and C++ strings can contain zeros. So I would suggest rb_str_new( string.data(), string.size() )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.