在visual basic 2008中创建COM dll并在C ++项目中使用它

时间:2011-07-28 15:57:16

标签: c++ vb.net visual-studio-2008

我按照这个tuorial在Visual Basic中创建了一个COM dll。 http://www.codeproject.com/KB/COM/Basics_of_Idl_file.aspx

我现在想在C ++项目中使用这个dll。我使用OLE / COM Viewer创建.idl文件,如本教程后半部分所述。 http://www.codeproject.com/KB/COM/vb_from_vc.aspx

我使用midl编译器编译了.idl,并包含了在我的c ++项目中创建的.h文件。

这是我的Visual Basic代码

<ComClass(MyComClass.ClassId, MyComClass.InterfaceId, MyComClass.EventsId)> _
Public Class MyComClass

#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 = "46604f8a-85a2-4027-9728-0390534c9209"
    Public Const InterfaceId As String = "30274029-711d-459a-9270-f9d73ad8737f"
    Public Const EventsId As String = "5e234d69-5263-4001-86ff-c475b113a77d"
#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
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub
    Public Sub DisplayMessage()
        MsgBox("Hello from MyComClass!")
    End Sub
End Class

这是我的c ++代码

    // Declare an HRESULT and a pointer to the clsVBTestClass interface

HRESULT     hr;
_MyComClass *IVBTestClass = NULL;

// Now we will intilize COM

hr = CoInitialize(0);

// Use the SUCCEEDED macro and see if we can get a pointer 

// to the interface

if(SUCCEEDED(hr))
{
    hr = CoCreateInstance( CLSID_MyComClass,
                NULL,
                CLSCTX_INPROC_SERVER,
                IID__MyComClass, 
                (void**) &IVBTestClass);

    // If we succeeded then call the CountStringLength method, 

    // if it failed then display an appropriate message to the user.

    if(SUCCEEDED(hr))
    {
        long        ReturnValue;
        _bstr_t     bstrValue("Hello World");

        // We can test this HR as well if we wanted to

        hr = IVBTestClass->DisplayMessage();

        hr = IVBTestClass->Release();
    }
    else
    {

    }
}
// Uninitialize COM

CoUninitialize();

编译c ++项目时收到以下错误

  

错误LNK2001:未解析的外部符号_CLSID_MyComClass   错误LNK2001:未解析的外部符号 IID _MyComClass

有人可以帮我弄清楚我做错了吗?

1 个答案:

答案 0 :(得分:1)

如果您没有完成创建类型库的最后部分,那很重要。

然后,您需要在C ++代码中使用#import语句来使用.tlb文件(如果类型库嵌入在dll中,则为.dll,这很常见)。

#import相当于包含带有COM的头文件,但会自动生成.tlh文件(标题)和.tli(实现)。