I would like to translate this C++ code into Nim
# starting point (C++)
struct Foo {
int i;
};
struct Bar : Foo {
int j;
};
The most obvious way I can see is
# first attempt in Nim
type
Foo {.inheritable} = object
i: int
Bar = object of Foo
j: int
Which works fine, but adds a pointer to the beginning of the resulting C++ struct
# generated C++, simplified
struct Foo {
TNimType* m_type
int i;
};
struct Bar : Foo {
int j;
};
This doesn't work for my use-case, because the library I am working with provides me with a memory blob and requires me cast it to my type. So I need to replicate the C++ type exactly, without extra bytes at the beginning.
If I was providing the blob to the library, I could increase the pointer by sizeof[TNimType] bytes and it would work. But because I am receiving the blob, I have no control over the memory location, so I can't manually add a TNimType pointer without copying the whole thing somewhere else to make room at the beginning.
So I need to recreate the type in Nim in a manageable way.
For now, I just used the magic of copy and paste, which works fine, but will become tedious rather quickly (the real Foo is loooong and gets used in lots of different places).
# tedious workaround
type
Bar = object of Foo
i: int
j: int
I would love to just replicate the inheritance syntax without the extra pointer, but I have no idea where to start- template? macro?
# desired syntax
type
Foo = object
i: int
Bar = object myNewKeyword Foo
j: int
Help much appreciated!
You can use the pure pragma, which will remove that header:
type
Foo {.pure inheritable.} = object
i: int
Bar = object of Foo
j: int