Skip to content

Gendarme.Rules.Interoperability.DoNotAssumeIntPtrSizeRule(2.10)

Sebastien Pouliot edited this page Feb 9, 2011 · 3 revisions

DoNotAssumeIntPtrSizeRule

Assembly: Gendarme.Rules.Interoperability
Version: 2.10

Description

This rule checks for code which casts an IntPtr or UIntPtr into a 32-bit (or smaller) value. It will also check if memory read with the Marshal.ReadInt32 and Marshal.ReadInt64 methods is being cast into an IntPtr or UIntPtr. IntPtr is generally used to reference a memory location and downcasting them to 32-bits will make the code fail on 64-bit CPUs.

Examples

Bad example (cast):

int ptr = dest.ToInt32 ();
for (int i = 0; i < 16; i++) {
    Marshal.StructureToPtr (this, (IntPtr)ptr, false);
    ptr += 4;
}

Bad example (Marshal.Read*):

// that won't work on 64 bits platforms
IntPtr p = (IntPtr) Marshal.ReadInt32 (p);

Good example (cast):

long ptr = dest.ToInt64 ();
for (int i = 0; i < 16; i++) {
    Marshal.StructureToPtr (this, (IntPtr) ptr, false);
    ptr += IntPtr.Size;
}

Good example (Marshal.Read*):

IntPtr p = (IntPtr) Marshal.ReadIntPtr (p);

Notes

  • This rule is available since Gendarme 2.0 but was named DoNotCastIntPtrToInt32Rule before 2.2
Clone this wiki locally