What is the simplest way to create and call dynami

2019-02-07 16:27发布

I want to fill a map with class name and method, a unique identifier and a pointer to the method.

typedef std::map<std::string, std::string, std::string, int> actions_type;
typedef actions_type::iterator actions_iterator;

actions_type actions;
actions.insert(make_pair(class_name, attribute_name, identifier, method_pointer));

//after which I want call the appropriate method in the loop

while (the_app_is_running)
{
    std::string requested_class = get_requested_class();
    std::string requested_method = get_requested_method();

    //determine class
    for(actions_iterator ita = actions.begin(); ita != actions.end(); ++ita)
    {
        if (ita->first == requested_class && ita->second == requested_method)
        {
            //class and method match
            //create a new class instance
            //call method
        }
    }
}

If the method is static then a simple pointer is enough and the problem is simple, but I want to dynamically create the object so I need to store a pointer to class and an offset for the method and I don't know if this works (if the offset is always the same etc).

The problem is that C++ lacks reflection, the equivalent code in a interpreted language with reflection should look like this (example in PHP):

$actions = array
(
     "first_identifier" => array("Class1","method1"),
     "second_identifier" => array("Class2","method2"),
     "third_identifier" => array("Class3","method3")
);

while ($the_app_is_running)
{
     $id = get_identifier();

     foreach($actions as $identifier => $action)
     {
         if ($id == $identifier)
         {
             $className = $action[0];
             $methodName = $action[1];

             $object = new $className() ;

             $method = new ReflectionMethod($className , $methodName);
             $method -> invoke($object);    
         }
     }
 }

PS: Yes I'm trying to make a (web) MVC front controller in C++. I know I know why don't use PHP, Ruby, Python (insert your favorite web language here) etc?, I just want C++.

8条回答
Melony?
2楼-- · 2019-02-07 17:19

You can also use dynamic loading of the functions:

Use GetProcAddress in Windows, and dlsym in Unix.

查看更多
太酷不给撩
3楼-- · 2019-02-07 17:22

You can try using factory or abstract factory design patterns for the class, and a function pointer for the function.

I found the following 2 web pages with implementations when I was searching for solutions for a similar problem:

Factory

Abstract factory

查看更多
登录 后发表回答