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
微信
Q Q
空间
微博