【问题标题】:C++ std::string to Ruby VALUEC++ std::string 到 Ruby VALUE
【发布时间】:2012-04-18 15:20:49
【问题描述】:

如何将 C++ std::string 对象转换为 Ruby VALUE 对象?

我试过rb_str_new2(c_string),但没用。

我有一个函数

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

并给出错误消息:

cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’

【问题讨论】:

  • 怎么没用?你的代码是什么?
  • rb_str_new2(string_object.c_str());应该可以轻松完成这项工作。
  • 如果你的变量不是 C 字符串,为什么要调用你的变量c_string? oO
  • @Matheus,Jakub 感谢您的帮助。

标签: c++ ruby ruby-1.9.3 ruby-c-extension


【解决方案1】:

您正在将 std::string 传递给函数,但它需要一个以 null 结尾的 const char *

std::string::c_str()成员函数可以用来获取一个:

rb_str_new_cstr(string.c_str());

【讨论】:

  • 这和rb_str_new2有什么区别?找不到很多关于rb_str_new_cstr的情报
  • @NiklasB,they are the same function。我更喜欢rb_str_new_cstr,因为我可以推断出该函数将 C 字符串作为参数。
  • 是的,我认为它可能只是一个更具描述性的别名。谢谢,很高兴知道,将来会使用它:)
  • @MatheusMoreira Ruby 字符串和 C++ 字符串可以包含零。所以我建议 rb_str_new(string.data(), string.size())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
相关资源
最近更新 更多