Daniel Lee
Daniel Lee

Reputation: 199

Why does VB Len(x) report different value than C# System.Runtime.InteropServices.Marshal.SizeOf(x)?

VB:

Structure WAVEFORMATEX
    Dim FormatTag As Short
    Dim Channels As Short
    Dim SamplesPerSec As Integer
    Dim AvgBytesPerSec As Integer
    Dim BlockAlign As Short
    Dim BitsPerSample As Short
    Dim Size As Short
End Structure

C#:

    struct WAVEFORMATEX
    {
        public short FormatTag;
        public short Channels;
        public int SamplesPerSec;
        public int AvgBytesPerSec;
        public short BlockAlign;
        public short BitsPerSample;
        public short Size;
    }

VB Len() returns 18. C# System.Runtime.InteropServices.Marshal.SizeOf() returns 20. Any idea why?

Upvotes: 1

Views: 65

Answers (1)

Charlieface
Charlieface

Reputation: 71603

Docs on Strings.Len state:

If an Object contains any other type, it will return the size of the object as it will be written to the file by the FilePut function.

This uses a quite compacted format.

Whereas Marshal.SizeOf is used for size calculations for Interop, with for example Marshal.StructureToPtr. This can often pad out small values to 32 or 64 bits, adding to the size.

So the algorithm is different because the end purpose is different.

Upvotes: 2

Related Questions