Search code examples
c#cominteropreturn-typeidl

Return value in IDL


I'm learning how to write C# from IDL and what I don't get is why the return value is defined in the parameter list as [out, retval]. Common sense tells me that HRESULT should be the return type but it doesn't seem to have any effect on the code in C#.


Solution

  • COM does not support exceptions. They are a very strong language runtime implementation detail, a C# exception is not anything like a C++ exception. That makes HRESULT very important, it is the substitute. Every COM method should return an error code, a negative value indicates failure.

    But many languages do support exceptions. Allowing the language runtime to turn a failure HRESULT into an exception. So the return value is no longer needed.

    Which allows the type library importer and the CLR to rewrite the method signature. Making it look like a "normal" function, one that has a useful return value. The [retval] attribute indicates this. Without one it becomes a normal method that returns void.

    Also explains the relevance of the [PreserveSig] attribute, it suppresses this rewriting. Occasionally necessary when the HRESULT returns more than just 0 to indicate success. COM iterators require it for the Next() method for example.