Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COM `HRESULT` is wrapped into an Exception in .NET

(preliminary note: I'm not yet fully up to speed with the whole 'interop' thing...)

When using a COM library from within .NET, all HRESULT methods are wrapped into something that throws when the return code is not SUCCEEDED.

//ATL magic exluded
class C {
    HRESULT foo(){ return E_FAIL; }
};

// usage code:
if( SUCCEEDED( c.foo() ) ) {
   // success code
} else {
   // failure code
}

The .NET counterpart of this code reads:

try {
   c.foo();
   // success code
} catch ( Exception e ) {
   // failure code
}

Is there a way to access the COM return code directly in .NET, so that no exception handling is needed?

like image 645
xtofl Avatar asked Jun 16 '11 11:06

xtofl


People also ask

What is Hresult in exception C#?

Each exception is mapped to a distinct HRESULT. When managed code throws an exception, the runtime passes the HRESULT to the COM client. When unmanaged code returns an error, the HRESULT is converted to an exception, which is then thrown by the runtime.

What is a System exception class?

The SystemException is a predefined exception class in C#. It is used to handle system related exceptions. It works as base class for system exception namespace. It has various child classes like: ValidationException, ArgumentException, ArithmeticException, DataException, StackOverflowException etc.


1 Answers

Yes, but you'll have to manually define the interop interface (rather than use tlbimp.exe) and use the PreserveSig attribute on the methods in question.

For example:

[ComImport]
[Guid("your-guid-here")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMyComInterface
{
     [PreserveSig]
     int DoSomething(out int result);
}

That is the equivalent of a COM method with the signature HRESULT DoSomething([out, retval] int *result);

If your interface is very complicated or you get stuck on how to define the interop interface, I recommend using tlbimp.exe, then using Reflector or ILSpy or something similar to decompile the generated interfaces, and then edit those to your liking. Saves work, too. :)

like image 87
Sven Avatar answered Oct 23 '22 02:10

Sven