使用 CoCreateInstance 从C++调用 COMVisible VB.Net dll

Calling COMVisible VB.Net dll from C++ using CoCreateInstance

本文关键字:VB Net dll COMVisible 调用 CoCreateInstance C++ 使用      更新时间:2023-10-16

自从我上一个问题以来,我得到了以下项目要编译。 它基于 https://stackoverflow.com/a/10949784/846550

但是,在运行时,对 CoCreateInstance 的调用会失败。 HRESULT 是0x80131522 - 谷歌为此,大多数点击似乎与我没有使用的 SQL 服务器有关。

C++代码,非托管

#include <iostream>
#include <atlbase.h>
#import "..ClassLibrary1bindebugClassLibrary1.tlb" no_namespace
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    ATLENSURE_SUCCEEDED(CoInitialize(NULL));
    CLSID clsid;
    _ComClass1 *t; 
    ATLENSURE_SUCCEEDED(::CoInitialize(NULL));
    ATLENSURE_SUCCEEDED(CLSIDFromProgID(OLESTR("ClassLibrary1.ComClass1"), &clsid));
    HRESULT hr = CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,
                                   __uuidof(_ComClass1),(LPVOID*) &t);
    ATLENSURE_SUCCEEDED(hr);
    ATLENSURE_SUCCEEDED(t->showform());
    ATLENSURE_SUCCEEDED(t->increment());
    CoUninitialize();
    return 0;
}

这是用于良好度量的 DLL 代码 - 几乎完全自动生成为 VB 中的 COM DLL 类。 (DLL 也显示为使用 oleview 注册)。

<ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> _
Public Class ComClass1
#Region "COM GUIDs"
    ' These  GUIDs provide the COM identity for this class 
    ' and its COM interfaces. If you change them, existing 
    ' clients will no longer be able to access the class.
    Public Const ClassId As String = "46783a4a-5ca9-4930-addb-cde91a377c02"
    Public Const InterfaceId As String = "e2ad7298-7339-45fb-aad1-cb82188bf067"
    Public Const EventsId As String = "b7e10cdf-dc2a-4052-9b0f-f6f9d5a1f0ac"
#End Region
    ' A creatable COM class must have a Public Sub New() 
    ' with no parameters, otherwise, the class will not be 
    ' registered in the COM registry and cannot be created 
    ' via CreateObject.
    Public Sub New()
        MyBase.New()
    End Sub

    Private f1 As Form1
    Public Sub showform()
        f1 = New Form1()
        f1.Show()
    End Sub
    Public Sub increment()
        f1.ProgressBar1.Increment(5)
    End Sub
End Class
这是一个

TypeLoadException,HRESULT 0x80131522是COR_E_TYPELOAD

这意味着 CLR 找不到您的程序集。它需要复制到与可执行文件相同的目录中、路径中或在 GAC 中注册。

REGASM的文档说:

使用 Regasm.exe 注册程序集后,可以将其安装在全局程序集缓存中,以便可以从任何 COM 客户端激活它。如果程序集仅由单个应用程序激活,则可以将其放在该应用程序的目录中。

  • http://msdn.microsoft.com/en-US/library/tzat5yw6(v=vs.71).aspx

也就是说,除非它安装在客户端的应用程序目录中、路径中、使用 /codebase 参数注册或安装在 GAC 中,后两者都需要强名称,否则它将无法创建。

FWIW,使用/codebase 参数不需要强命名。