Click to See Complete Forum and Search --> : C# COM client error handling
definition
September 29th, 2005, 04:42 AM
hey guys, im looking for some information on how to handle exceptions within a C# client from a C++ COM server. I'm use to error handling in C++ and am not quite sure what to do with being able to say SUCCEEDED or have the HRESULT available to me. how do i manage this in C#? anyone know?
p.s sorry if this should be in the C# section, but it is a bit of both worlds.
Siddhartha
September 29th, 2005, 04:43 AM
[ redirected ]
Regards,
Siddhartha
darwen
September 29th, 2005, 05:57 AM
If an HRESULT returns an error code then a COMException is thrown. The property ErrorCode on this exception gives the error code.
e.g.
uint hResult = 0;
try
{
// make COM call here
}
catch (COMException exception)
{
hResult = exception.ErrorCode;
}
return hResult;
I'm unsure if it throws this exception if S_FALSE is returned : you'll have to try it out.
Alternatively, you can do your own COM interop as shown in my article.
http://www.codeguru.com/Csharp/Csharp/cs_misc/com/article.php/c9065/
Define [PreserveSig] on each method and an exception will not be thrown : the HRESULT will be passed back.
e.g.
[Guid("----")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITestInterface
{
[PreserveSig] uint MyMethod();
}
Darwen.
Siddhartha
September 29th, 2005, 06:30 AM
S_FALSE, S_OK, and S_* in general are success return codes.
E_FAIL, E_POINTER, and E_* in general are error return codes.
An Error returned by a Native C++ COM Server will throw an exception in the C# client.
Success (even if S_FALSE) will not.
Attached is a sample ATL C++ COM Server accessed by a C# client.
Should you return E_FAIL in CDialogInterface::Show (exposed via IDialogInterface), you will get an unhandled exception - one that needs to be handled via the technique in the previous post.
In general, the sample displays a Dialog implemented in a C++ COM Server invoked via a C-Sharp client.
Detailed explanation of the sample is in my post here (http://www.codeguru.com/forum/showthread.php?p=1233999#post1233999).
(Ah, it seems that you have already seen it!)
On a side note - in C++, the macro SUCCEEDED returns TRUE for S_FALSE as well - reason being that S_FALSE is also a return code implying SUCCESS.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.