views:

69

answers:

2

I have an application in VC++ which needs to execute a function provided to it (function name entered in a text box) from a COM DLL (file name provided in another text box).

I have seen code for loading a Win32 library using LoadLibrary and GetProcAddress.

How can this be done for a COM DLL file (created in Visual Basic 6.0)? Is there a link where I can get more information?

A: 

There's a C++ example of LoadLibrary And GetProcAddress for a COM dll here http://stackoverflow.com/questions/2187425/how-do-i-use-a-com-dll-with-loadlibrary-in-c/2187806#2187806

John Knoeller
A: 

If the component that you're calling supports IDispatch (which is quite likely if it was created in VB), you can use late binding to call COM interface methods dynamically.

For example:

IDispatch *pDispatch;
// Assumes pUnknown is IUnknown pointer to component that you want to call.
HRESULT hr = pUnknown->QueryInterface(IID_IDispatch, reinterpret_cast<void **>(&pDispatch));
if(SUCCEEDED(hr))
{
    DISPID dispid;
    // Assumes sMethodName is BSTR containing name of method that you want to call.
    hr = pDispatch->GetIDsOfNames(IID_NULL, &sMethodName, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
    if(SUCCEEDED(hr))
    {
        // Assumes that the method takes zero arguments.
        VARIANT vEmpty;
        vEmpty.vt = VT_EMPTY;
        DISPPARAMS dp = { &vt, 0, 0, 0 };
        hr = pDispatch->Invoke(dispid, IID_INULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dp, 0, 0, 0);
    }

    pDispatch->Release();
}

This example fetches the DISPID of the named method from IDispatch::GetIDsOfNames(), then calls that method by passing the DISPID to IDispatch::Invoke().

For the sake of clarity, I've assumed that there are no arguments to the method you want to call, but you can modify the DISPPARAMS structure that is passed to Invoke() if there are.

Phil Booth