c# - COM Interop 未通过接口(interface)检测 .NET 函数

标签 c# .net com

我有一个 .NET 程序集,我已经执行了 regasmgacutil。我还有一个 COM interop,我正在尝试使用 .NET 程序集。但是,通过我的 pDotNetCOMPtr 我无法“检测”我的 .NET 公共(public)接口(interface)上的任何方法。当我尝试使用 Visual Studio 2010 进行编译时,MFC COM DLL 一直说 _SslTcpClientPtr 中没有名为 Encrypt 的方法。我使用的是 .NET 4.0 Framework。想法?

COM/MFC

extern "C" __declspec(dllexport) BSTR __stdcall Encrypt(BSTR encryptString)
{   
    CoInitialize(NULL);

    ICVTnsClient::_SslTcpClientPtr pDotNetCOMPtr;

    HRESULT hRes = pDotNetCOMPtr.CreateInstance(ICVTnsClient::CLSID_SslTcpClient);

    if (hRes == S_OK)
    {
        BSTR str;

        hRes = pDotNetCOMPtr->Encrypt(encryptString, &str);     

        if (str == NULL) {
            return SysAllocString(L"EEncryptionError");
        }
        else return str;    
    }

    pDotNetCOMPtr = NULL;

    return SysAllocString(L"EDLLError");

    CoUninitialize ();
}

.NET

namespace ICVTnsClient
{
    [Guid("D6F80E95-8A27-4ae6-B6DE-0542A0FC7039")]
    [ComVisible(true)]
    public interface _SslTcpClient
    {
        string Encrypt(string requestContent);
        string Decrypt(string requestContent);        
    }

    [Guid("13FE33AD-4BF8-495f-AB4D-6C61BD463EA4")]
    [ClassInterface(ClassInterfaceType.None)]
    public class SslTcpClient : _SslTcpClient
    {

       ...
       public string Encrypt(string requestContent) { // do something }

       public string Decrypt(string requestContent) { // do something }

    }
  }
}

最佳答案

那是因为你忘记了 [InterfaceType] 属性,这样接口(interface)就可以提前绑定(bind),并且方法名出现在类型库中。修复:

[Guid("D6F80E95-8A27-4ae6-B6DE-0542A0FC7039")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface _SslTcpClient
{
    // etc..
}

ComInterfaceType.InterfaceIsDual 允许它是早期和晚期绑定(bind)。 Microsoft 更喜欢默认的 IsIDispatch,它使用后期绑定(bind)的方式更少。

关于c# - COM Interop 未通过接口(interface)检测 .NET 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11007792/

相关文章:

c - 如何确定当前进程中 COM 使用的内部 HWND?

c# - 如何防止重复项目listView C#

c# - 如何以编程方式为 EntityDataSource 和 DetailsView 设置参数?

.net - 来自带有事务的 dotnet 的 SQL 脚本

.net - Wpf 用户控件和 MVVM

C++/CLI 与 COM——哪个更好?

c# - 使用 WPF 在列表框项目上移动 + 单击功能

c# - 以编程方式构建项目

c# - 如何将两个字母的国家/地区代码转换为标记表情符号?

c# - 来自具有最佳性能的 C++ 应用程序的 API