初始化com对象的问题

Issue with initializing COM object

本文关键字:问题 对象 com 初始化      更新时间:2023-10-16

我编译了以下VB代码,并获取了DLL(" testvb.dll"(和tlb(" testvb.tlb"(文件作为输出。

Imports System
Imports System.Runtime.InteropServices
Namespace TesterNS
    <ComVisible(True),
    Guid("4B673F5A-A953-4C20-9A90-8F94ED2F6DDF"),
    InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
    Public Interface _Tester
        Function GetMonth() As Integer
    End Interface
    <ComVisible(True),
    Guid("FEC833EE-37E9-4406-9344-8A8BD5C43B07"),
    ClassInterface(ClassInterfaceType.None),
    ProgId("Tester.Numbers1")> Public Class Tester
        Implements _Tester
        Public Tester()
        Public Function GetMonth() As Integer Implements _Tester.GetMonth
            GetMonth = DateTime.Now.Month
        End Function
    End Class
End Namespace

我选择了

注册com Interop

在VB项目的项目设置中选项。

我正在尝试从C 代码访问上述功能。我在c 中的stdafx.h文件中包括以下导入语句。

#import "TestVB.tlb" no_function_mapping, no_namespace, named_guids

并尝试访问COM对象如下:

HRESULT hr = CoInitialize(NULL);
_TesterPtr t1 = NULL;
CLSID cls;
std::string s = "";
bool flag = false;
hr = CLSIDFromProgID(L"Tester.Numbers1", &cls);
if (SUCCEEDED(hr))
{
    hr = CoCreateInstance(cls, NULL, CLSCTX_INPROC_SERVER, __uuidof(_Tester), (void**)&t1);
    if (SUCCEEDED(hr))
        s = "success";
    else
        s = "fail";
}

我看到hr = REGDB_E_CLASSNOTREG Class not registered拨打CoCreateInstance呼叫后的错误。

我不确定我在做什么错。

在我的C 应用程序中,在CoInitialize(NULL)之前有一个呼叫AfxOleInit()。如果我删除了CoInitialize(NULL)的呼叫,我就可以使其正常工作。