1
votes

I have a .NET Library registered for COM Interop which I successfully use from VB6 code (so, it's propperly registered and this is not the issue).

What happens is that I'm trying to use this same library via C++ code (an MFC ActiveX Control) and I'm not even being able to instantiate the object (yes, it has a parameterless constructor).

Imagine that the namespace is Foo and the name of the class is Bar. How would I instantiate such object? I'm trying this:

On the .h file:

Foo::Bar *obj;

On the .cpp file, on the constructor of the ActiveX control:

obj = new Foo::Bar();

And I'm getting the following errors:

  • «incomplete type is not allowed"»;
  • «error C2027: use of undefined type 'Foo::Bar'».

So basically my question is: How does one use .NET COM Interop objects from C++ code?

2
You are not close to writing correct C++ code. Start with the #import directive to get closer, a book will certainly not hurt either. - Hans Passant
I'm using the #import directive, obviously. I've omitted it because I thought it would be obvious for everyone. I'm familiar with C++, not with Windows or COM Interop. - amgcgoncalves

2 Answers

2
votes
CComObject<Foo::Bar>* obj;
HRESULT hr = CComObject<Foo::Bar>::CreateInstance(&obj);
//check hr

Or perhaps if you want to use an interface called IBar that Bar implements:

CComPtr<Foo::IBar> pIObj;
HRESULT hr = pIObj.CreateInstance(__uuidof(Foo::Bar));
//check hr

And as Hans suggested in his comment, you're going to want to use the #import directive to import the type library.

1
votes

in C++, first you should initialize the COM, then get the COM object through UUID, the you can use the function of this COM object, after it is done, uninitialize the COM. So the the code will be like this:

CoInitialize(NULL);

IMyClassPtr myClass = IMyClassPtr(_uuid(myClass));
if (myClass != NULL)
   {
     myClass->DoSomething();
 }

 CoUnitialize();