none
COM HRESULTs RRS feed

  • Question

  • Hi,

    I read that when you use COM functions, the runtime will automatically throw an appropriate exception if the hresult <> 0.  Is this correct?  i.e. I shouldn't need to check the return result from any COM method (i.e. StgOpenStorageOnILockBytes, etc.).

     

    My second question is about using other methods from Win32, such as GlobalLock.  Is there a CLR equivalent of this?  I'm currently using something like this:

     

     

    Code Snippet
    [DllImport("kernel32.dll")]
    static extern IntPtr GlobalLock(IntPtr hMem);

     

     

     

    ... with GlobalLock returning IntPtr.Zero if it fails.  What should I do in this case?  Which exception should I throw (to keep my application consistent, I don't want to use return codes here).

     

    Thanks.

    Thursday, May 29, 2008 6:04 PM

Answers

  •  By default it's true for method calls that go through COM interop (ie COM interface methods), but not for calls via PInvoke (declared with the DllImport attribute, such as your StgOpenStorageOnILockBytes). You can adjust this behavior with the PreserveSig attribute.

    There's no BCL equivalent of GlobalLock AFAIK. If GlobalLock fails it should return error information via GetLastError. So I would add SetLastWin32Error=true to your DllImport attribute, and then throw a Win32Exception on failure.

    Mattias, C# MVP
    • Marked as answer by RobinsonUK Friday, May 30, 2008 9:33 AM
    Friday, May 30, 2008 6:54 AM
    Moderator

All replies

  •  By default it's true for method calls that go through COM interop (ie COM interface methods), but not for calls via PInvoke (declared with the DllImport attribute, such as your StgOpenStorageOnILockBytes). You can adjust this behavior with the PreserveSig attribute.

    There's no BCL equivalent of GlobalLock AFAIK. If GlobalLock fails it should return error information via GetLastError. So I would add SetLastWin32Error=true to your DllImport attribute, and then throw a Win32Exception on failure.

    Mattias, C# MVP
    • Marked as answer by RobinsonUK Friday, May 30, 2008 9:33 AM
    Friday, May 30, 2008 6:54 AM
    Moderator
  • Sounds entirely reasonable to me.  Thanks Mattias.
    Friday, May 30, 2008 9:33 AM