What's the difference between a non-unmanaged type and a managed type?

谁都会走 提交于 2019-11-30 12:52:03

问题


When I wrote the following snippet for experimenting purposes, it raised the hover-error (see screenshot):

Cannot declare pointer to non-unmanaged type 'dynamic'

The snippet:

dynamic* pointerToDynamic = &fields;

While the code is clearly not allowed (you cannot take the address of a managed type), it raised with me the question: what is a non-unmanaged type and how is it different to a managed type? Or is it just Visual Studio trying to be funny?


回答1:


There is a difference between unmanaged and non-managed pointers.

A managed pointer is a handle to an object on the managed heap, and AFAIK is available in managed C++ only. It is equivalent of C# reference to an object. Unmanaged pointer, on the other hand, is equivalent of a traditional C-style pointer, i.e. address of a memory location; C# provides unary & operator, fixed keyword and unsafe context for that.

You are trying to get a pointer to a managed field (dynamic is actually System.Object is disguise), while C# allows pointers to unmanaged objects only, hence the wording: your type is non-unmanaged.

A bit more on this here.

Update: to make it more clear, managed C++ supports classic C-style pointers and references. But to keep C++ terminology consistent, they are called unmanaged and managed pointers, correspondingly. C# also supports pointers (explicitly in unsafe context) and references (implicitly whenever objects of reference types are involved), but the latter is not called "managed pointers", they are just references.

To sum up: in C++ there are unmanaged and managed pointers, in C# - unmanaged pointers and references.

Hope it makes sense now.




回答2:


You cannot create a pointer to a managed type. While int, double, etc are managed, they have unmanaged counterparts.

So what non-unmanaged type really means is the managed type.

The problem here is that the managed type since is sitting on the heap, you cannot get a pointer to. You can get a pointer using fixed keyword but that is mainly for arrays.



来源:https://stackoverflow.com/questions/9941320/whats-the-difference-between-a-non-unmanaged-type-and-a-managed-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!