Search code examples
c#exceptioncominterophresult

How to get HRESULT instead exception from a COM-method


I'm using the IAMCameraControl.GetRange method in C#. The description says nothing about exceptions. Only about returning the HRESULT error value. But in my code a COMException occurs, inside of which an HRESULT is specified. Why throw an exception instead of returning an error? How to fix it?

[ComVisible(true)]
[ComImport]
[Guid("C6E13370-30AC-11d0-A18C-00A0C9118956")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMCameraControl
{
    int GetRange([In] CameraControlProperty property, [In][Out] ref int pMin, [In][Out] ref int pMax, [In][Out] ref int pSteppingDelta, [In][Out] ref int pDefault, [In][Out] ref int pCapsFlag);
    int Set([In] CameraControlProperty property, [In] int lValue, [In] int flags);
    int Get([In] CameraControlProperty property, [In][Out] ref int lValue, [In][Out] ref int flags);
}

Solution

  • Just use PreserveSig attribute

    [ComImport, Guid("c6e13370-30ac-11d0-a18c-00a0c9118956"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IAMCameraControl
    {
        [PreserveSig]
        int GetRange(...)
        
        ...
    }