Ansis Māliņš
Ansis Māliņš

Reputation: 1704

How does Marshal.ReadInt32 etc. differ from unsafe context and pointers?

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];

Upvotes: 6

Views: 1019

Answers (2)

David Heffernan
David Heffernan

Reputation: 613302

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.

Upvotes: 0

leppie
leppie

Reputation: 117280

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.

Upvotes: 1

Related Questions