Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

unmanaged

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];
like image 433
Ansis Māliņš Avatar asked Jul 27 '11 11:07

Ansis Māliņš


1 Answers

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.

like image 77
leppie Avatar answered Sep 30 '22 11:09

leppie