本文介绍了使用C#指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何C#使得指针的使用?如果C#是一种管理语言,垃圾收集做得很好,在preventing内存泄漏和正确释放内存,那么什么是用C#指针和如何效果的不安全 是什么人?

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 is the effect of using pointers in c# and how "unsafe" are they?

推荐答案

要使用指针,你必须允许不安全的code和标记使用指针为不安全。然后,你必须解决的指针在内存中,以确保垃圾回收器不会移动它们:

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) {
    // ...
}

这是不安全的,因为,从理论上说,你可以采取一个指针,遍历整个地址空间,并破坏或改变内部CLR数据结构,比方说,换一个方法实现。你可以这样做,在管理code。

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.

这篇关于使用C#指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:23