简体   繁体   中英

Calling strings as functions in C++

I'm writing a 'skeleton' front-end in native C++ for other users where the users are creating functions that I will 'call' depending on arguments that are passed in. For example:

skeleton.exe /foo param1

would be used to call the function "int doFoo(param1){return 0;}" inside my skeleton. As more team members write functions, I would need to add those functions as well.

A stray thought I had - and I'm not even certain if this would be possible - would be to have a resource file - or, maybe, a resource xml file - that would list the command line arguments, the number of parameters and then the function I need to call for that parameter. So my resource file for the above would look like:

foo 1 doFoo

This way, as people create their functions, all they have to do is add it to the resource file.

The problem I am running into - and what I'm wondering if it is even possible - is whether I can 'interpret' that 'doFoo' as a function if it is read from the resource file. Is there anything that would allow me to 'interpret' a string as a function I can call?

You will need to map strings to function pointers.

One method is to create a lookup table another is to use std::map .

Search the internet for "c++ dispatch" and maybe "c++ double dispatch".

I think I've got it! I just need to ensure that each added function is declared with extern "C" __declspec(dllexport) ! Example:

extern "C" __declspec(dllexport) int square(int x)
{
    return (x*x);
}

typedef int(__cdecl *MYPROC)(int);

int _tmain(int argc, _TCHAR* argv[])
{
    LPCSTR funcName = "square";
    HMODULE hMod = GetModuleHandle(NULL);
    if (hMod != NULL)
    {
        cout << "hMod is not NULL!" << endl;
        MYPROC abstractSquare = (MYPROC)GetProcAddress(hMod, funcName);

        if (NULL != abstractSquare)
        {
            cout << "abstractSquare is not NULL!" << endl;
            int y = (abstractSquare)(10);
            cout << "y = " << y << "!" << endl;
        }
        else
        {
            cout << "abstractSquare is NULL!" << endl;
        }
    }
    else
    {
        cout << "hMod is NULL!" << endl;
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM