我以为我知道如何做到这一点,但显然不是,所以我希望得到一些帮助! 我无法让我的 dll 注册,所以我可以在 VBS 或其他地方实例化它。
我编写了以下示例类,选中“使程序集 COM 可见”,选中“为 COM Interop 注册”,然后构建它。 当我尝试从 VBS 实例化它时,出现“Activex 组件无法创建对象”错误。
这是类代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Smurf
{
public class Pants
{
public string Explode(bool Loud)
{
string result;
if (Loud)
result = "BANG";
else
result = "pop";
return result;
}
}
}
...这是 VBS:
Dim a
Set a = CreateObject("Smurf.Pants")
msgbox("ok")
我还需要做什么?
谢谢:)
[编辑]
忘记提及,在第一次失败后我尝试了 REGSVR32 和 REGASM - 没有帮助!
[/编辑]
请注意,当我尝试 REGSVR32 时,我收到此消息:
模块“C:...\Smurf.dll”已加载,但未找到入口点 DllRegisterServer。 确保“C:...\Smurf.dll”是有效的 DLL 或 OCX 文件,然后重试。
这有多大帮助??
这是最新版本的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Smurf
{
[Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")]
public interface IPants
{
[DispId(1)]
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
{
public Pants() { }
[ComVisible(true)]
[ComRegisterFunction()]
public static void DllRegisterServer(string key) { }
[ComVisible(true)]
[ComUnregisterFunction()]
public static void DllUnregisterServer(string key) { }
[ComVisible(true)]
public string Explode(bool Loud)
{
string result;
if (Loud)
result = "BANG";
else
result = "pop";
return result;
}
}
}
最佳答案
这里可能有一些不同的东西在起作用。首先,您需要在提升的命令提示符下使用带有/codebase/tlb 开关的 regasm 工具(假设是 Windows Vista、7 或 Windows Server 2008)。像这样的东西:
regasm "Path to Smurf.dll" /codebase /tlb
一旦您使用 regasm 注册了 dll,您应该能够使用 VBS、VBA 或 VB6 调用它。
我能够使用 VBA 中的早期绑定(bind)和后期绑定(bind)来调用 Explode
方法。然而,当我从 VBScript 尝试时,我收到了“ActiveX 无法像您那样创建对象错误。”
我在 Windows 7 64 位上运行,我记得这可能会导致在编译为 32 位 dll 并在 64 位操作系统上运行它们时出现问题。一时兴起,我启动了命令提示符并输入:
C:\Windows\SysWow64\CScript.exe "Path to VBScript"
结果是脚本正确运行并在屏幕上显示“Pop”。
这是我使用的稍微简化的 C# 代码以及 VBScript 文件的内容。
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;
}
}
}
VB脚本:
Dim x
Set x = CreateObject("Smurf.Pants")
MsgBox (x.Explode(False))
Set x = Nothing
关于c# - 为 COM Interop 公开 dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11570262/