Search code examples
c++cominterfacecreateinstance

How to conditionally choose the C# class I invoke via COM in my C++ DLL?


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.


Solution

  • 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