gpt4 book ai didi

.net - 无法访问 VBA 中的 COM 公开方法

转载 作者:行者123 更新时间:2023-12-04 07:56:59 25 4
gpt4 key购买 nike

我正在尝试访问 VBA 中的 COM 公开方法。

问题:我在 VBA 中看到了所有默认方法(如 GetHashCodeGetTypeToString ),但不是作为 COM 接口(interface)一部分且专门编写为 COM 可见的方法(如 getStringValue() 下面)。

设置详情:

  • Visual Studio 2008
  • Windows 7 x64
  • 办公室 2007
  • .NET 3.5

  • 接口(interface)“IGetMyString.cs”
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace SimpleCOMAssembly
    {
    [ComVisible(true), GuidAttribute("4153A1AC-ECE9-4f66-B56C-1DDEB6514D5D")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    interface IGetMyString
    {
    [DispId(1)]
    string getStringValue();
    }
    }

    实现“GetMyString.cs”
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.ComponentModel;

    namespace SimpleCOMAssembly
    {
    [ComVisible(true), GuidAttribute("0A3D4D65-CF50-4020-BF13-77001F8AAABE")]
    [ProgId("SimpleCOMAssembly.GetMyString")]
    [ClassInterface(ClassInterfaceType.None)]
    public class GetMyString : IGetMyString
    {
    public GetMyString() { }

    [ComVisible(true), Description("Get my string")]
    public string getStringValue()
    {
    return "hello";
    }
    }
    }

    在构建属性中,我检查了 '使程序集 COM 可见' (见下面的快照)

    enter image description here

    还要求 Visual Studio 2005 制作 '注册 COM 互操作' (见下面的快照)

    enter image description here

    最后,作为构建后事件,我正在运行 regasm.exe 来注册 .DLL 以及 .TLB 到注册表,如下所示:
    %SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm /codebase "$(TargetPath)" /tlb:"$(TargetDir)$(TargetName).lib"

    在 Excel 对象资源管理器 View 中,我启用了 COM 服务器(上面写的 SimpleCOMAssembly),现在在对象资源管理器中它没有列出 COM 接口(interface)方法(见下文)
    enter image description here

    有人可以帮助我知道我缺少什么导致 COM 接口(interface)方法未在 VBA 中显示吗?

    编辑
    附加生成的 TLB 的 ITypeLib View
    enter image description here

    最佳答案

    Excel 对象浏览器屏幕截图清楚地显示了一个问题。请注意 GetHashcode、GetType 和 ToString 方法是如何可见的。这些是从 System.Object 继承的方法。但是您的代码段明确(并且正确)使用 [ClassInterface(ClassInterfaceType.None)] 以便隐藏类实现。

    它没有隐藏。不太清楚这是怎么发生的,早期尝试的旧类型库可以解释它。但是您的构建步骤非常可疑,您提供的帮助太多了。 “使程序集类型 COM 可见”选项是强制构建系统公开 .NET 类型的一种非常粗略的方法。但是您的代码正在使用精炼的右上角-pinky-up-when-you-drink-tea 方式向 COM 公开类型。其中包括 [ComVisible(true)] 属性,复选框的作用,以及 [ClassInterface] 属性,这是复选框不做的。

    所以问题是你要求构建系统实现两个接口(interface)。无论它从基类继承什么,在你的例子中是 _Object,加上它从声明中继承的,在你的例子中是 IMyGetString。这很好,并且与 COM 完全兼容,但 VBA 不是一个很好的 COM 使用者。它只喜欢 [Default] 界面,在您的情况下就是 _Object 。从截图中清晰可见。

    所以关闭“使程序集 COM 可见”选项。

    并在调用 Regasm 的构建后事件或“注册 COM 互操作”复选框之间进行选择。两种方式都这样做只会使您不知道为什么它不起作用的几率增加一倍。只有在需要为 64 位版本的 Office 注册程序集时才需要 postbuild。

    关于.net - 无法访问 VBA 中的 COM 公开方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574973/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com