Overloading a method in com visible dll

2019-07-24 16:22发布

问题:

I am creating a COM visible dll and I was trying to overload a method.

So basically this code:

[ComVisible(true)]
[ProgId("TAF.TextLog")]
[Guid("af3f89ed-4732-4367-a222-2a95b8b75659")]
public class TextLog
{
    String _logFilePath;

    public TextLog()
    {
    }

    [ComVisible(true)]
    public void Create(string filePath)
    {
        String path = Path.GetDirectoryName(filePath);
        if (Directory.Exists(path))
        {
            _logFilePath = filePath;
        }

    [ComVisible(true)]
    public void Write(string message)
    {
        WriteMessage(null, message, AlertMsg.MsgTypes.Info);
    }

    [ComVisible(true)]
    public void Write(string title, string message, AlertMsg.MsgTypes messageType)
    {
        WriteMessage(title, message, messageType);
    }

    private void WriteMessage(string title, string message, AlertMsg.MsgTypes messageType)
    {
        using (StreamWriter file = new StreamWriter(_logFilePath, true))
        {
            if (title == null)
                file.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}\t{1}", DateTime.Now, message));
            else
                file.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss}\t{1}\t{2}\t{3}", DateTime.Now, title, message, messageType));
        }
    }
}

Looks like this is not possible however. If I call .Write from the calling program (which is a very simple VBSCript by the way), i get an error that my parameters are not correct.

This is the calling VBscript code:

Set myObj = CreateObject("TAF.TextLog")
myObj.Create("C:\temp\textlog.txt")
myObj.Write "title", "test message 1", 1

If I have only one .Write method in the dll it works fine. Can someone tell me if overloading like this is even possible in a dll?

回答1:

COM does not have support for member overloads, each name must be unique. An inevitable side-effect of IDispatch::GetIDsOfNames(). The function that the script interpreter uses to translate "Write" as used in the scripting code to a dispid. The method still exists, there's just no way to get GetIDsOfNames() to return its dispid. The type library exporter solves this problem by renaming the overloaded method, it will be Write_2().

No workaround for that when you use late-binding afaik, you must avoid overloads.



回答2:

COM doesn't really support overloading.

See http://msdn.microsoft.com/en-us/library/ms182197(v=vs.80).aspx