Could anyboby help me with the alternative solution in C# regarding AddressOf operator in VB6? AddressOf returns a long value. What way can I get the output in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Expanding on Harper Shelby's answer, yes it can be done, but it's generally a code smell to do so in .NET.
To get the address of a variable in C#, you can use C-style pointer (*) /address (&) / dereference (->) syntax. In order to do this, you will have to compile the app with the /unsafe compiler switch, as you're bouncing out of the safety net of managed code as soon as you start dealing with memory addresses directly.
The sample from MSDN tells most of the story:
This assigns the address of the
number
variable to the pointer-to-an-intp
.There are some catches to this:
fixed
to pin the variable in RAM.int* p = &GetSomeInt();
)Generally, my advice in this world is to seriously consider why you think you need to do this in the .NET world. One of .NET's missions was to shield developers from going against the metal, and this feature is counter to that mission. It exists for those (rare) scenarios where it is needed; if you find yourself frivolously using this simply because you can, you're probably mis-using it and introducing code smell.
Avoid it if possible, but know how to use it if you absolutely must.
C# has special syntax for assigning functions to delegates/events. Just use
<delegate> += <function>;
If you're actually trying to get the address for some other use, you're out of luck. One of the things about managed code is that these addresses aren't necessarily fixed. While it would be unlikely that most functions would ever change there are circumstances where it's possible.
Both notation are equivalent.
Apparently, this can be done (though I'm not sure where you'd need it). Here's the MSDN page.