Search code examples
c#c++comcom-interop

C# COM vs C++ COM return value


I'm building a COM component C#, the customer can set binary data. It would be nice if the COM component returns exception rather than error code, but realized it would be difficult to handle exception in (Delphi, C + + and JScritp). I chose it receives a data in hexadecimal (internally convert to binary) and return in hexadecimal (internally convert binary to hexadecimal).
The method getData can return the data and a error code, the question is: how to do this in C# interop?

in C++ COM exists the HRESULT

HRESULT getData([in] int __position, [out,retval] BSTR* __data); // can Return __data or error -1 data not exists
HRESULT setData([in] BSTR __data, [out,retval] int* __status);

but in C# COM ??

int getData ??? // return __status or __data;
int setData(String __data); // return __status;

thanks in advanced,


Solution

  • You should return an HRESULT from each COM method and return the data in out parameters. However, the COM interop layer shields this from you by automatically translating between COM HRESULT error codes and C# exceptions. I think your code should really look like this:

    MIDL

    HRESULT getData([out,retval] BSTR* pData);
    HRESULT setData([in] BSTR data);
    

    C#

    String getData();
    void setData(String data);
    

    The key point is that the COM function return value is always an HRESULT. If the function succeeds then S_OK is returned—otherwise you an appropriate error code that describes the reason for failure is returned. The true return value, data in this example, is returned through an out parameter rather than the return value. But of course, the COM interop layer hides that implementation detail from you.

    Your question appears to suggest that you wish for the return value to be either an HRESULT in case of failure, or a string in case of success. This is not possible since function return values are statically typed.