Explicit DLL function calling any function

I’m trying to make a experimental interpreted language based on this tutorial http://compilers.iecc.com/crenshaw/ but in C++. Now I want to implement a system for calling dll functions at runtime, for this I’m trying use explicit linking in C++. But the type of data and the amount of arguments is undefined, it depends of the code processed by the interpreter, I already tried to use variadic function(because the unknown amount of arguments) and void pointers(because the unknown type of parameter) but it still don’t works.

The below code is just a test for later be implemented in my project:

typedef VOID* (WINAPI *_DLLPROC)(...); // it's variadic because the parameters are undefined

// I Tried to do it using variadic (like this)
// VOID* CallDllFunction(LPCWSTR dllName, LPCSTR funcName, int numArgs, ...)

VOID* CallDllFunctionA(LPCWSTR dllName, LPCSTR funcName, void* val1, void* val2, void* val3, void* val4)
{
    //va_list ap; // I tried to use variadic
    //
    HINSTANCE hinstLib = LoadLibrary(dllName);
    VOID* retVal;
    _DLLPROC func = (_DLLPROC)GetProcAddress(hinstLib, funcName); 
    //
    //va_start(ap, numArgs);
    if (hinstLib != NULL)
    {
        try
        {
            retVal = (func)(val1, val2, val3, val4);
        }
        catch (...)
        {
            throw;
        }
    }
    else
    {
        cout << "Error!" << endl;
    }
    //va_end(ap);
    //
    FreeLibrary(hinstLib); 
    //
    return retVal;
}

int main( void ) 
{ 
    CallDllFunctionA(L"User32.dll", "MessageBoxA", 0, "Hello", "Title", MB_OK);


    printf("n");
    system("PAUSE");

    return 0;
}

The above code show the message box:

enter image description here

but then displays this error message:

enter image description here

Probably the above error is caused because the parameters are void* wherein would be the correct types (HWND, LPCSTR, LPCSTR and UINT), but the values are undefined.

So, how can i make a function for call any dll function with any name, any type, any amount of parameters? Is it possible? How the others languages (such as python, ruby) do it during runtime?


Source: dll

Leave a Reply