views:

128

answers:

2

After much help from all my StackOverFlow brethren, I managed to create a C++ DLL that calls my C# classes via COM and passes data back and forth to an external application. There was much celebration in the kingdom after that code started working.

Now I have a new problem. I'm expanding the DLL so that it can call different classes (all implementing the same interface). I need to decide what class to call depending on a char array passed to the DLL when it is loaded. The methods I call are exactly the same regardless of which class I use. What is the best way to switch between classes when calling the DLL?

 // Initialize COM. 
 HRESULT hr = CoInitialize(NULL);



// I want to do something like this....but how? 
if (strcmp(modelType, "Model1") == 0) { 
     IUnitModelPtr pIUnit(__uuidof(ClassOne));
    } 

    if (strcmp(modelType, "Model2") == 0) { 
     IUnitModelPtr pIUnit(__uuidof(ClassTwo));
    }


//call method 1

//call method 2

CoUninitialize();

//exit

This is probably a fairly simple question, but I really do not know any C++. Just getting COM going was a major challenge for me.

edit: Im sure there are some super elegant ways to achieve this (reflection?) but please limit your suggestions to stuff that can be implemented easily....efficiency is not important here and maintainability is not really an issue.

+2  A: 

Do smth like this:

GUID classId = GUID_NULL;
if( strcmp( modelType, "Model1" ) == 0 ) {
    classId = __uuidof( class1 );
} else if( strcmp( modelType, "Model2" ) == 0 ) {
    classId = __uuidof( class2 );
} else if(... etc, continue for all possible model types
}
IUnitModelPtr unit;
unit.CreateInstance( classId );
// interface methods can be called here
sharptooth
Thanks, this is exactly what I needed.
Alex
+1  A: 

Two options.

As each different interface implementation is a coclass, and your C++ code uses the right prog-id/classid to perform the create.

Alternately the exposed coclass is a factory with a method to return the actual implementation class.

Both need logic to map your modelType to implementation class. You can do this in the C++ code or in the .NET code. Without more information about the overall context (is the string --> coclass mapping logically part of the COM component or of the caller).

(In a pure C++ COM implementation you can create your own custom COM instance factory, but that's more advanced COM and not available for .NET COM interop.)

Richard
Creating a factory in c# would have been the best way to go (the string->coclass mapping is logically part of the COM component), but time is limited so the quick fix wins. Thanks for your response though, if I ever have to do this again i'll do it the proper way!
Alex