views:

50

answers:

2

I am confused in AddressOf in c# and pointer in c++ ? Am i right that Addressof is manage execution and pointer is unmanage execution or something else?

+1  A: 

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."

Himanshu
+2  A: 

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.

RossFabricant