Guest User

Untitled

a guest
Apr 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #include <rice/Class.hpp>
  2. #include <rice/Constructor.hpp>
  3. #include <rice/Object.hpp>
  4. #include <string>
  5. using namespace Rice;
  6.  
  7. // Basic testing implementation to show the following
  8. // code works.
  9. class Color {
  10. public:
  11. Color() { name = "Color";}
  12. Color(int r, int g, int b) {}
  13. Color(int r, int g, int b, int a) {}
  14. void setName(std::string name) { this->name = name; }
  15. std::string to_string() const { return name; }
  16.  
  17. private:
  18. std::string name;
  19. };
  20.  
  21. // This method needs the "self" right now, or you get invalid number
  22. // of arguments.
  23. // This will be changed in the next version of Rice.
  24. Color* color_from_string(Object self, std::string name) {
  25. Color* c = new Color();
  26. c->setName(name);
  27. return c;
  28. }
  29.  
  30. // The crux of the issue is that you need to explicitly define
  31. // how Rice is to convert from the Color class in C++ to Ruby and back.
  32. // The following two methods do this.
  33. Data_Type<Color> rb_cColor;
  34.  
  35. template<>
  36. Color* from_ruby<Color*>(Object x) {
  37. Color* c;
  38. Data_Get_Struct(x.value(), Color, c);
  39. return c;
  40. }
  41.  
  42. template<>
  43. Object to_ruby<Color*>(Color * const & c) {
  44. return Data_Wrap_Struct(rb_cColor, 0, Default_Allocation_Strategy<Color*>::free, c);
  45. }
  46.  
  47. extern "C"
  48. void Init_static_methods()
  49. {
  50. rb_cColor = define_class<Color>("Color")
  51. .define_constructor(Constructor<Color>())
  52. .define_method("to_s", &Color::to_string)
  53. .define_singleton_method("[]", &color_from_string);
  54. }
Add Comment
Please, Sign In to add comment