Struct/Class metadata for object representation and managed/unmanaged interaction

Viewed 78

I know there is plenty of similar questions, but I want to understand very specific aspects that are never mentioned anywhere. In both cases: managed (NET runtime in this case) and native /unmanaged (c, cpp, etc)

Taken from here: https://adamsitnik.com/Value-Types-vs-Reference-Types https://i.stack.imgur.com/0Qtnu.png

enter image description here

The first issue that not just wasn't glossed over but not even mentioned is how your code/runtime supposed to know what type of struct you are dealing with? If struct is just all its data packed together, then where is metadata about what type of struct it is? Okay, may be in case of managed .NET runtime and binaries it is easier, it is part of the IL, but what about native binary code? It gets stripped 100%, if you open it for text reading there is no function or struct names in you binary. How would you know runtime what the struct you receive and how to treat/ parse it if there is no struct metadata with it? The pointer just points at memory, but there is no struct' structure and members there stored. At least class can be identified by extra data it has (object header and method table).

Things get even more confusing when you receive struct data from unmanaged/native space. You NEED to have that data embedded into struct otherwise how would you know what you receive? And I can't even begin to understand* how would this work for something like classes, because they are thousandfold more complex. How do you even return class from unmanaged space?

1 Answers

If struct is just all its data packed together, then where is metadata about what type of struct it is?

There isn't any. With raw value data - whether that means an individual value, or an array/vector/whatever, the consuming code is the thing that knows how to interpret it. What it is is just: bytes.

How would you know runtime what the struct you receive and how to treat/ parse it if there is no struct metadata with it?

Because it is defined in the API, either in a signature, or with human words such as "the pointer refers to the start of len elements of type Foo"

You NEED to have that data embedded into struct

No you don't; you just need to agree in advance what you are sending/receiving. This is how the vast majority of interactions between different codebases works, and has always worked. Having object metadata is the exception, not the norm.

How do you even return class from unmanaged space?

You wouldn't, if by "classes" in this context you mean managed objects.

Related