5
\$\begingroup\$

So I have this SDK I'm working with, which lives in unmanaged land, and when it wants to tell me something in particular it sends me a particular Windows API message and passes a pointer to a Date in the LParam of that message. I figured out that the date is OA-compatible (a double representing a fractional number of days since the epoch), and so after some playing around I came up with this:

  • Dereference the pointer by marshalling the raw bits at the address into an Int64.
  • Perform a bitwise conversion of the Int64 into a Double.
  • Treat that double as an OA Date and pass it to the static methods on DateTime to get the answer.

It totally works, but conceptually it sounds really kludgy; pointer, to long, to double (bitwise to boot), to DateTime. Other than inlining these three lines with only the final result being stored, is there any more direct way in .NET to turn an IntPtr to an OLE Date into a DateTime?

private void GetDateFromWinMsg(Message message)
    {
        ...
        var dateAsULong = Marshal.ReadInt64(message.LParam);
        var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong);
        var dateTime = DateTime.FromOADate(dateAsDouble);
        ...
    }
\$\endgroup\$
  • 3
    \$\begingroup\$ Doesn't look kludgy to me ...although that doesn't mean there isn't a shorter process. Think of each function as a tool - you need 3 tools to perform the conversion. \$\endgroup\$ – IAbstract Sep 16 '11 at 17:47
2
\$\begingroup\$

I agree with @IAbstract that the inline code looks fine. I would wrap it and name it differently since nothing in the current code reveals that it is a pointer to an OLE/OA Date.

public DateTime DateTimeFromOLEDatePointer(Int64 oaDate)
    {
        var dateAsULong = Marshal.ReadInt64(oaDate); 
        var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong); 
        var dateTime = DateTime.FromOADate(dateAsDouble); 
    } 

Usage:

private void GetDateFromWinMsg(Message message)
    {
        return DateTimeFromOLEDatePointer(message.LParam);
    }

Could also make it an extension method.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.