Should you use pointers (unsafe code) in C#?

2019-01-13 14:37发布

Should you use pointers in your C# code? What are the benefits? Is it recommend by The Man (Microsoft)?

11条回答
男人必须洒脱
2楼-- · 2019-01-13 15:25

If you have to.

Say that you need to false color a large grayscale image, say 2000x2000 pixels. First write the 'safe' version using GetPixel() and SetPixel(). If that works, great, move on. if that proves to be too slow, you may need to get at the actual bits that make up the image (forget about Color matrices for the sake of the example). There is nothing 'bad' about using unsafe code, but it adds complexity to the project and should thus be used only when necessary.

查看更多
唯我独甜
3楼-- · 2019-01-13 15:29

You should use them if you need them; mostly this will be when dealing with some tricky interop scenarios (for example when I wrote a managed wrapper for DPAPI in .NET 1.0 they were needed) but very occasionally it might be to improve performance (after profiling!) by using stackalloc or similar.

It is recommended by Microsoft in as much as they are the designers of C#, and they made the decision to add the capability to write unsafe code in it. You can see from the choice of keyword and the requirement to delineate the methods/classes in which you write it using the keyword, that it isn't designed to be the de-facto implementation choice.

查看更多
家丑人穷心不美
4楼-- · 2019-01-13 15:30

course it isn't "recommended", that's why it's labeled "unsafe". But don't let that scare you away. Although, it should make you look twice at your code. Perhaps there is a managed way to do it?

查看更多
闹够了就滚
5楼-- · 2019-01-13 15:32

Do it if it makes your code shorter and clearer.

"Follow your inclinations with due regard to the policeman round the corner." WSM

查看更多
别忘想泡老子
6楼-- · 2019-01-13 15:35

Reinterpretive like casts not supplied by BitConverter.
Specifically converting a unint into an int for hash functions where all you care about is the bits.

Using some useful, well reasoned about c or C++ idiomatic functions on structs where you need to treat them as a byte* of a well known length, again most useful for hashing.

Extremely fast binary serialization of (very specific) in memory structs (by doing it to an array of them) though to be honest this is better done by just dropping to C++/CLI.

It must be said that in many cases the task requiring pointers can often be solved better by doing it in C++/CLI and then importing this into you c# project as a dll. It doesn't change whether the code is 'safe' or not but it makes a bunch of useful functions for operating on pointer based structures more accessible. It also allows you to mess about with generic types or enums if you really want to.

The likelihood of most developers needing to do this is indeed remote. Useful when you need it though...

查看更多
登录 后发表回答