-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add "offsetof" to Struct classes (#83)
* Add "offsetof" to Struct classes I need to get the offset of a member inside a struct without allocating the struct. This patch adds an "offsetof" class method to structs that are generated. The usage is like this: ```ruby MyStruct = struct [ "int64_t i", "char c", ] MyStruct.offsetof("i") # => 0 MyStruct.offsetof("c") # => 8 ``` * Update test/fiddle/test_c_struct_builder.rb Co-authored-by: Sutou Kouhei <kou@cozmixng.org> Co-authored-by: Sutou Kouhei <kou@cozmixng.org>
- Loading branch information
1 parent
b150250
commit 4e3b60c
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# frozen_string_literal: true | ||
begin | ||
require_relative 'helper' | ||
require 'fiddle/struct' | ||
require 'fiddle/cparser' | ||
rescue LoadError | ||
end | ||
|
||
module Fiddle | ||
class TestCStructBuilder < TestCase | ||
include Fiddle::CParser | ||
|
||
def test_offsetof | ||
types, members = parse_struct_signature(['int64_t i','char c']) | ||
my_struct = Fiddle::CStructBuilder.create(Fiddle::CStruct, types, members) | ||
assert_equal 0, my_struct.offsetof("i") | ||
assert_equal Fiddle::SIZEOF_INT64_T, my_struct.offsetof("c") | ||
end | ||
|
||
def test_offset_with_gap | ||
types, members = parse_struct_signature(['void *p', 'char c', 'long x']) | ||
my_struct = Fiddle::CStructBuilder.create(Fiddle::CStruct, types, members) | ||
|
||
assert_equal PackInfo.align(0, ALIGN_VOIDP), my_struct.offsetof("p") | ||
assert_equal PackInfo.align(SIZEOF_VOIDP, ALIGN_CHAR), my_struct.offsetof("c") | ||
assert_equal SIZEOF_VOIDP + PackInfo.align(SIZEOF_CHAR, ALIGN_LONG), my_struct.offsetof("x") | ||
end | ||
|
||
def test_union_offsetof | ||
types, members = parse_struct_signature(['int64_t i','char c']) | ||
my_struct = Fiddle::CStructBuilder.create(Fiddle::CUnion, types, members) | ||
assert_equal 0, my_struct.offsetof("i") | ||
assert_equal 0, my_struct.offsetof("c") | ||
end | ||
end | ||
end if defined?(Fiddle) |