Marshal.ReadInt32 等与不安全上下文和指针有何不同?
特别是:元帅安全吗?指针更快吗?
int pixel = Marshal.ReadInt32(bitmapData.Scan0, x * 4 + y * bitmapData.Stride);
int pixel = ((int*)bitmapData.Scan0)[x + y * bitmapData.Stride / 4];
Particularly: Is Marshal safer? Are pointers faster?
int pixel = Marshal.ReadInt32(bitmapData.Scan0, x * 4 + y * bitmapData.Stride);
int pixel = ((int*)bitmapData.Scan0)[x + y * bitmapData.Stride / 4];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有什么区别。如果您查看
Marshal.ReadInt32
中的代码,您会发现它使用指针来执行相同的操作。Marshal
的唯一“好处”是您不必显式允许不安全代码。 IIRC,您还需要 FullTrust 才能运行不安全的代码,因此这可能是一个考虑因素。There is no difference. If you look at the code from
Marshal.ReadInt32
you will see it uses pointers to perform the same thing.The only 'benefit' with
Marshal
is that you not have to explicitly allow unsafe code. IIRC, you also require FullTrust to run unsafe code, so that may be a consideration.我个人更喜欢使用
Marshal
主要是因为我避开不安全的代码。至于哪个更快,我不确定,但我确信无论你怎么做,逐像素操作都可能会很慢。更好的方法是将整个扫描线读入 C# 数组并对其进行处理。I personally prefer using
Marshal
mostly because I shun unsafe code. As to which is faster, I'm not sure but I am certain that operating pixel by pixel is liable to be slow however you do it. Much better is to read an entire scanline into a C# array and work on that.