• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Ruby仿C结构体:CStruct的一些例子

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

1. [代码]最简单的例子     
# CStruct Examples
require 'cstruct'
 
# example:
# struct Point in C\C++        (32-bit platform): 
#
# struct Point
# {
#    int x;
#    int y;
# }; 
 
# struct Point in Ruby: 
class Point < CStruct
  int32:x
  int32:y
end
 
# create a Point's instance
point   = Point.new
 
# assign like as C language
point.x = 10
point.y = 20
 
puts "point.x = #{point.x},point.y = #{point.y}"
 
 
 
# struct PointF in C\C++        (32-bit platform): 
#
# struct PointF
# {
#    double x;
#    double y;
# }; 
 
# struct PointF in Ruby: 
class PointF < CStruct
  double:x
  double:y
end
 
# create a PointF's instance
# use 'block' to initialize the fields
point2   = PointF.new do |st|
        st.x = 10.56
        st.y = 20.78
end
 
puts "sizeof(PointF) = #{PointF.size}"
puts "point2.x = #{point2.x},point2.y = #{point2.y}"
2. [代码]数组成员     

# CStruct Examples
require 'cstruct'
 
# example:
# struct T in C\C++ (32-bit platform): 

# struct T
# {
#    int element[8];
# }; 
 
# struct T in Ruby: 
class T < CStruct
  int32:elements,[8]
end
 
# create a T's instance
t_array = T.new
 
(0..7).each do |i|
        t_array.elements[i] = i  # assign like as C language
endhttp://www.enterdesk.com/special/huangguantp/
 
# output皇冠图片
(0..7).each {|i| puts "t_array.elements[#{i}] = #{t_array.elements[i]}" }
 
 
# Actually,t_array.elements.class is Array. So..
t_array.elements.each {|element| puts element }
3. [代码]结构体嵌套     
# CStruct Examples
require 'cstruct'
# example:
# struct A in C\C++ (32-bit platform): 
# struct A{
#     struct Inner
#     {
#       int v1; 
#       int v2;
#     };
#     Inner inner;
# };
 
# struct A in Ruby:
class A < CStruct
    class Inner < CStruct
        int32 :v1
        int32 :v2
    end
        Inner :inner
end
 

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ruby 常见问题集 1 -----不断更新中发布时间:2022-07-14
下一篇:
寻找RubyonRails项目兼职开发人员-kevinhgy发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap