Overloads in COM interop (CCW) - IDispatch names include suffix (_2, _3, etc)

廉价感情. 提交于 2019-11-28 11:46:20

COM does not support method overloading, so .NET COM Interop layer has to improvise. I'm not sure if name mangling as you described as documented anywhere, but even if it is, I don't think that using it is a good idea - it's still pretty inconvenient API for COM users. If you want to expose your classes to COM, the best way is to write a distinct COM-friendly [ComVisible] interface, and hide the class itself. The correct way to handle overloads in a COM-friendly way would be have a single method with some [Optional] arguments (and delegate to your corresponding .NET overloads).

In my experience, having interop generate Method, Method_1, Method_2, etc. is normal and stable but not really desirable. It's annoying that overloads don't cross the Managed/Unmanaged boundary. Instead of having it arbitrarily add a numeric suffix to my methods, I try to refactor the COM-Visible methods into separate methods with unique names so it's more obvious to the COM consumer what is being called.

Yes, it's documented on MSDN:

Since changing it would be a "breaking change" of a documented feature, I guess you can rely on it being "stable". The big disadvantage is that your method names depend on the order in which they are defined in the source file.

Note, though, that COM supports optional arguments, so using them might be a viable alternative to overloads. If you need to add overloads to be binary-compatible to old .NET clients of your library, I found the following pattern to be useful:

// used for binary-compatibility with .NET clients who currently use 
// the old, one-parameter version
[ComVisible(false)]
void myMethod(String oneParameter) {   
    ... 
}   

// since this is the first COM-visible version, it is assigned the "correct" name.
void myMethod(String oneParameter, int newParameter = 0) {
    ...
}

Since COM supports optional parameters, both myMethod(string) and myMethod(string, int) will work.

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