开发者

What is the difference between AddressOf in c# and pointer in c++

I am confused in AddressOf in c# and pointer in c++ ? Am i right that Addressof 开发者_JS百科is manage execution and pointer is unmanage execution or something else?


AddressOf is a VB operator, and doesn't exist in C#. It creates a delegate to a procedure. The delegate can be used later to call the procedure in code that does not include the procedure's name.

A pointer in C/C++ is a representation of an address in memory. You can create a pointer to a function and use it to call that function, so in that particular case pointers and delegates behave similarly. However, delegates are not simply function pointers. The most important difference is that delegates can be chained, and call more than one procedure at once.


The sample from MSDN tells most of the story:

int number;
int* p = &number;
Console.WriteLine("Value pointed to by p: {0}", p->ToString());

This assigns the address of the number variable to the pointer-to-an-int p.

There are some catches to this: 1. The variable whose address you are fetching must be initialized. Not a problem for value types, which default, but it is an issue for reference types.

  1. In .NET, variables can move in memory without you being aware of it. If you need to deal with the address of a variable, you really want to use fixed to pin the variable in RAM.

  2. & can only be applied to a variable, not a constant nor a value. (In other words, you cannot use a construct like int* p = &GetSomeInt();)

  3. Again, your code must be compiled in unsafe mode, which flags the CLR that you will be using features outside the managed code "safety net."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜