Search code examples
c#com-interoptlbimp

Returning S_FALSE from a C# COM dll


I have a method defined in IDL as follows :

interface IMyFunc : IDispatch
{
    [id(1), helpstring("method GetNextFunction")] HRESULT GetNextFunction(
        [in,out] long* lPos, [out, retval] BSTR* bstrName);
}

Using C++ I always implemented this as follows :

STDMETHODIMP CMyFunc::GetNextFunction(long *nID, long *lPos, BSTR *bstrName)
{
    if ( function to return )
    {
        // setup return values;
        return S_OK;
    }
    else
    {
        // just exit
        return S_FALSE;
    }
}

Now I am implementing this in C# and have used tlbimp on the type library and ended up with :

public string GetNextFunction(ref int nID, ref int lPos)

I understand that this is because [out, retval] is used as the return type instead of the HRESULT as in C++. Is there a simple way to return the S_OK / S_FALSE values without changing the method definition? The only way I can see is that I have to use ildasm / ilasm to add preservesig so I end up with something like this :

public int GetNextFunction(ref int nID, ref int lPos, ref string bstrName)

I was wondering if there was some other way without doing the il compilation step.


Solution

  • Try passing the /PreserveSig flag to tlbimp. That should add the PreserveSigAttribute to the methods it generates. This is a new feature added to the latest version. More info is at the tlbimp CodePlex site.