Tuesday, June 13, 2006

Unmarshal Double with VB.NET

One might be suprised howto unmarshal double values got to VB.NET over P/Invoke.
Well, Double is 64bit value, but there's no explicit ReadDouble(...) method in Marshal. So the first try may look like:

Dim myDbl as Double = Convert.ToDouble(Marshal.ReadInt64(myPtr,myOffset))

It won't work!

Mind the bits have exponential as well as mantissa parts. These aren't available in Int64 and are guessed by .NET as missing. So all the bits contained in Int64 read are used for conversion and bring not the expected result.

Sample: you get over P/Invoke a Double value 20060610.0 (for what purposes ever). Read with ReadInt64 you get 4716150189222526976 as Int64, that easily converted to 4.716150189222527E+18 as Double.

Workaround: do not forget to use BitConverter!

Dim myDbl as Double = BitConverter.Int64BitsToDouble( _


No comments: