Returning S_FALSE from a C# COM dll

霸气de小男生 提交于 2019-12-10 17:45:15

问题


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.


回答1:


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.




回答2:


As mentioned in another answer, you can use the /PreserveSig flag to indicate that you want to attach the PreserveSig attribute to all of the methods that are exported on the interfaces that are generated.

If you don't want to apply the PreserveSig attribute to all of the methods, then you can easily define the COM interface in C# code and then apply the PreserveSig attribute and modify the signature of the functions accordingly. Then, you can cast the class implementations from your co classes in TLBIMP and work with your interface definition as you wish.



来源:https://stackoverflow.com/questions/2592684/returning-s-false-from-a-c-sharp-com-dll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!