Search code examples
.netvisual-c++dynamiccomidispatch

Get User-Defined Methods from IDispatch for Dynamic Assembly


So the program I'm working on creates a dynamic .Net assembly from source code that the user enters into a text editor (using CodeDOM as a compiler). I need to get an IDispatch for this assembly that contains all of the user-defined methods.

For example, the user may enter this:

Imports System.Windows.Forms
Public Class Test
    Function Hello
        MessageBox.Show("Hello, World!")
    End Function
End Class

This creates an in-memory assembly that I can reference. The code I'm using to get the IDispatch:

//"file" the pointer to the in-memory assembly, "name" is the name of the type being created
HRESULT ScriptEngine::GetDispatch(void** disp) {
    Object^ component = file->CreateInstance(name);
    if (file != nullptr) {
        *disp = Marshal::GetIDispatchForObject(component).ToPointer();
        return S_OK;
    else
        return E_FAIL;
}

This successfully gets an IDispatch for me, but it doesn't contain any user-defined methods. Instead, it only contains the six default IDispatch methods (QueryInterface, GetTypeInfo, etc.). I need to be able to get defined methods, such as "Hello" from the previous example.

How do I get an IDispatch that contains the user-defined methods from this assembly?


Solution

  • IDispatch interface contains only four methods: GetIDsOfNames, GetTypeInfo, GetTypeInfoCount and Invoke. If each component would have different IDispatch then it would not be a single interface, would it?

    IDispatch is an interface for dynamic, late bound method execution, which supports introspection, i.e. ability to find metadata about a type at run-time. It provides a way to dynamically find a list of supported methods and properties and to dynamically invoke them. This means that those methods are not part of the interface itself: instead you can enumerate them via first three methods listed above, and execute them via Invoke.