Skip to content

Instantly share code, notes, and snippets.

@def-
Last active September 10, 2020 16:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save def-/2ed28c3be686fb02fa2d to your computer and use it in GitHub Desktop.
Save def-/2ed28c3be686fb02fa2d to your computer and use it in GitHub Desktop.
template offset(Typ, member): int {.immediate.} =
var dummy: Typ
cast[int](dummy.member.addr) -% cast[int](dummy.addr)
type Foo = object
x: int
y: int
echo offset(Foo, y)
@HugoP707
Copy link

a more correct and updated way of doing it would be this:

template offset(Typ, field: untyped): ByteAddress =
  var dummy: Typ
  cast[ByteAddress](dummy.field.addr) -% cast[ByteAddress](dummy.addr)

type Foo = object
  x: int
  y: int

echo offset(Foo, y)

(i changed the argument name because i liked it more, the other one are fine too)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment