Skip to content

Commit

Permalink
Add offsetof so we can get the offset of members
Browse files Browse the repository at this point in the history
I want to get the offset of fields inside structs, but I don't want to
instantiate the struct.  I need to embed the offsets inside machine
code, and I can't get the offsets without calling `new` on the struct.

This commit adds an `offset` method so you can get the offset of a
member without instantiating anything.  You can do:

```ruby
C.rb_control_frame_t.offsetof(:sp) #=> 8
```

I don't think this implementation is perfect, you can only get immediate
fields.  But it is better than nothing!
  • Loading branch information
tenderlove committed Jan 20, 2023
1 parent 887d216 commit 06b62cb
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/ruby_vm/mjit/c_pointer.rb
Expand Up @@ -54,6 +54,12 @@ def self.define(sizeof, members)
# Return the size of this type
define_singleton_method(:sizeof) { sizeof }

# Get the offset of a member named +name+
define_singleton_method(:offsetof) { |name|
_, offset = members.fetch(name)
offset / 8
}

define_method(:initialize) do |addr = nil|
if addr.nil? # TODO: get rid of this feature later
addr = Fiddle.malloc(sizeof)
Expand Down

0 comments on commit 06b62cb

Please sign in to comment.