C#不安全/固定code [英] C# Unsafe/Fixed Code

查看:156
本文介绍了C#不安全/固定code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给出一个很好的时间实际使用不安全和固定在C#code的例子吗?我已经打了过,但从来没有真正找到了一个很好的利用它。

Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it.

考虑这个code ...

Consider this code...

fixed (byte* pSrc = src, pDst = dst) {
    //Code that copies the bytes in a loop
}

相比,单纯用...

compared to simply using...

Array.Copy(source, target, source.Length);

二是在.NET Framework中的code,第一的code从微软网站复制的一部分,<一个href="http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx">http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx.

内置的Array.Copy()是明显比使用不安全code更快。这可能只是因为第二个是刚刚好,并写在第一只是一个例子,但什么样的情况下,你会真的甚至需要使用不安全/固定code代表什么?抑或是这个可怜的网页开发人员玩弄的东西在他的头上?

The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?

推荐答案

这对互操作与非托管code有用。传递给非托管函数指针的任何需要修复(又名为钉),以prevent垃圾回收器重新定位底层内存。

It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory.

如果您在使用P / Invoke,那么默认的编组将针对象为您服务。有时需要进行自定义编组,有时有必要针的对象不是单P的持续时间较长/ Invoke调用。

If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call.

这篇关于C#不安全/固定code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆