Read this question today about safe and unsafe code I then read about it in MSDN but I still don't understand it. Why would you want to use pointers in C#? Is this purely for speed?
相关问题
- 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
I tend to avoid it, but there are some times when it is very helpful:
For example of the last, I maintain some serialization code. Writing a
float
to a stream without having to useBitConverter.GetBytes
(which creates an array each time) is painful - but I can cheat:Now I can use shift (
>>
) etc to writei
much more easily than writingf
would be (the bytes will be identical to if I had calledBitConverter.GetBytes
, plus I now control the endianness by how I choose to use shift).There is at least one managed .Net API that often makes using pointers unavoidable. See SecureString and Marshal.SecureStringToGlobalAllocUnicode.
The only way to get the plain text value of a
SecureString
is to use one of theMarshal
methods to copy it to unmanaged memory.There are three reasons to use unsafe code:
Sometimes you'll need pointers to interface your C# to the underlying operating system or other native code. You're strongly discouraged from doing so, as it is "unsafe" (natch).
There will be some very rare occasions where your performance is so CPU-bound that you need that minuscule extra bit of performance. My recommendation would be to write those CPU-intesive pieces in a separate module in assembler or C/C++, export an API, and have your .NET code call that API. An possible additional benefit is that you can put platform-specific code in the unmanaged module, and leave the .NET platform agnostic.