ComVisible in C++/CLI

2019-03-27 17:50发布

问题:

i'm converting C++ to C++/CLI and would like to expose some managed classes as COM objects. In C# it was easy and setting [ComVisible] & inheriting from interface (also ComVisible) did the job. However C++ project build as C++/CLI does not export DllRegisterServer.

Here is sample project (started from CLR Console Application project in VS 2008).

#include "stdafx.h"

using namespace System;
using namespace System::Runtime::InteropServices;

[ComVisible(true)]
[Guid("E3CF8A18-E4A0-4bc3-894E-E9C8648DC1F0")]
[InterfaceType(ComInterfaceType::InterfaceIsDual)]
public interface class ITestInterface
{
    void TestMethod();
};


[ComVisible(true)]
[Guid("1514adf6-7cb0-4561-9fbb-b75c0467149b")]
public ref class CliComClass : ITestInterface
{
    public: 
        virtual void TestMethod() 
        {
        }
};

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
    return 0;
}

When I run regsvr32 on output .exe I got error saying DllRegisterServer was not found. I've tried google for some help but with no success.

回答1:

You need to use TlbExp instead, TlbExp is the tool use to export managed classes to COM, it will read the assembly find the ComVisible type and register them.