Using C# Pointers

后端 未结 3 756
死守一世寂寞
死守一世寂寞 2021-01-11 17:24

How does c# makes use of pointers? If C# is a managed language and the garbage collector does a good job at preventing memory leaks and freeing up memory properly, then what

3条回答
  •  清歌不尽
    2021-01-11 18:17

    To use pointers you have to allow unsafe code, and mark the methods using pointers as unsafe. You then have to fix any pointers in memory to make sure the garbage collector doesn't move them:

    byte[] buffer = new byte[256];
    
    // fixed ensures the buffer won't be moved and so make your pointers invalid
    fixed (byte* ptrBuf = buffer) {
        // ...
    }
    

    It is unsafe because, theoretically, you could take a pointer, walk the entire address space, and corrupt or change the internal CLR data structures to, say, change a method implementation. You can't do that in managed code.

提交回复
热议问题