14

I know in C++/CLI one cannot use unmanaged types when defining a managed class:

public struct Unmanaged
{
    int x;
    int y;
};

public ref class Managed
{
    int one;
    Unmanaged two;  //error C4368
};

I do not understand why though. Unmanaged is simply a collection of native types - its size is known, surely it (and by it I mean the block of memory that defines it) would be moved around with the 'block of memory' that is Managed inside the 'managed heap', and whatever offset is stored in the metadata will remain valid, no? Just as if an integer or a float were declared?

Why can we not mix types?

sebf
  • 2,831
  • 5
  • 32
  • 50
  • Who do you expect to be able to answer such a question authoritatively? – ildjarn May 09 '12 at 20:02
  • @ildjarn well, I was just going to check out the C++/CLI source code and write up a nice answer... owait – Dagg Nabbit May 09 '12 at 20:06
  • 1
    I am afraid I don't get it; someone with more knowledge of the workings C++/CLI than I? When designing the compiler, someone must've had the same assumption that I assert in my post (or the assumption is completely wrong!), and then realised that for some condition it did not hold true, hence the error - I was just curious as to what that condition was. In the blog post Tony linked it was explained that the allocation of native types on the managed heap was disallowed to stop people abusing pin_ptr to return those 'instances' to unmanaged code. – sebf May 09 '12 at 21:51

1 Answers1

16

Mixed type actually refers to the mixed memory models. Unmanaged types go on the heap, managed types go in the garbage collected heap, so when you embed an unmanaged type in a managed, it would require memory on both heaps, which is why you do this sort of thing with a pointer. The pointer is managed, the value it points to isn't.

I was curious myself, so I gathered up my google and found this.

http://blogs.msdn.com/b/branbray/archive/2005/07/20/441099.aspx

Guy seems to know what he's talking about.

Good question though...

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
  • There is some great information in that post, thank you very much! It makes me wonder how many other language characteristics have been designed solely to prevent programmers making mistakes (I count one in C# at least; no fall through cases in switch statements) – sebf May 09 '12 at 21:46
  • The link seems outdated. – mradul dubey Apr 25 '22 at 12:15