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);
 ...
 }
Heslacher
50.9k5 gold badges83 silver badges177 bronze badges
asked Sep 16, 2011 at 17:02
\$\endgroup\$
1
  • 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\$ Commented Sep 16, 2011 at 17:47

1 Answer 1

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.

answered Jan 16, 2012 at 17:17
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.