Sunday, March 1, 2015

C HRESULT comparison

Thanks to Rick Strahl for this great blog entry that saved me a lot of time solving a COM Interop issue:


COMException exposes this HRESULT as an int value in the Exceptions ErrorCode property. Now in my brain freeze haze I tried something like this:

try{ this.OutputBuffer = this.ComInstance.GetType().InvokeMember("ProcessHit", BindingFlags.InvokeMethod, null, this.ComInstance, new object[1] { this.CompleteInputBuffer }) as string;}catch (COMException ex){ // *** RPC Server Unavailable if ( ex.ErrorCode == 0x800706ba ) { // try to reload the server if (this.LoadServer()) return this.CallComServer(); } this.ErrorMessage = ex.Message; return false;}catch (Exception ex){ this.ErrorMessage = ex.Message; return false;}finally{ this.EndRequest();}

Now that seems like it should work well enough right?

Eh, not quite. The problem is that the constant hex value is created as a uint while the HRESULT is a signed integer. The code compiles just fine but at runtime the comparision may fail (depending on the HRESULTs actual value - high values like the one above (and arent just about all COM errors 0x800... ) will fail.

So quick - how do you create a signed hex constant?

I dont know, but this works as expected:

if ( (uint) ex.ErrorCode == 0x800706ba )
for details click below

No comments:

Post a Comment