Expose dll for COM Interop

↘锁芯ラ 提交于 2019-12-03 07:05:12

There could be a few different things at play here. First, you'll want to use the regasm tool with the /codebase /tlb switch from an elevated command prompt (assuming Windows Vista, 7 or Windows Server 2008). Something like:

regasm "Path to Smurf.dll" /codebase /tlb

Once you have registered the dll using regasm you should be able to invoke it using VBS, VBA or VB6.

I was able to use early binding and late binding from VBA to call the Explode method. However, when I tried from VBScript I received the "ActiveX can't create object error as you did."

I'm running on Windows 7 64 bit, and I recalled that this can cause problems when compiling to 32 bit dlls and running them on 64 bit operating systems. On a whim, I fired up a command prompt and entered:

C:\Windows\SysWow64\CScript.exe "Path to VBScript"

The result was that the script ran correctly and displayed "Pop" on screen.

Here's the somewhat simplified C# code I used as well as the contents of the VBScript file.

namespace Smurf
{
    [Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")]
    public interface IPants
    {
        string Explode(bool Loud);
    }

    [Guid("7BD20046-DF8C-44A6-8F6B-687FAA26FA71"),
     InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IPantsEvents
    {
        string Explode(bool Loud);
    }

    [ComVisible(true)]
    [Guid("0D53A3E8-E51A-49C7-944E-E72A2064F938")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces(typeof(IPantsEvents))]
    public class Pants : IPants
    {

        [ComVisible(true)]
        public string Explode(bool Loud)
        {
            string result;
            if (Loud)
                result = "BANG";
            else
                result = "pop";
            return result;
        }
    }
}

VBScript:

Dim x 
Set x = CreateObject("Smurf.Pants")
MsgBox (x.Explode(False))
Set x = Nothing
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!