Skip to content

How to implement offsetof? #110

Answered by edubart
codehz asked this question in Q&A
Aug 27, 2021 · 2 comments · 1 reply
Discussion options

You must be logged in to vote

I will show 5 possible ways to achieve that:

local MyRecord = @record{
  a: uint32,
  b: uint32
}

-- First way, poly function using C `offsetof` (known only at runtime, calculated by the C compiler)
local function c_offsetof(T: type, field: string <comptime>): isize <inline>
  local off: isize <noinit>
  ##[[
  cinclude '<stddef.h>'
  local type, field = T.value, field.value
  cemit(function(emitter)
    emitter:add_indent_ln('off = offsetof(', type, ', ', field, ');')
  end)
  ]]
  return off
end
assert(c_offsetof(MyRecord, 'b') == 4)

-- Second way, poly function (known at runtime, calculated by the Nelua compiler)
global function func_offsetof(T: type, field: string <comptime>): integer 

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@edubart
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by edubart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants