从其名称的字符串生成派生类实例。 (即反射) [英] Generating a derived class instance from a string of its name. (i.e, reflection)

查看:173
本文介绍了从其名称的字符串生成派生类实例。 (即反射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个基类:

class Base 
{
public:
virtual void Test()=0;
};

,在动态加载的模块(.so / .dll) this:

and, in a dynamically loaded module (.so/.dll), I implemented a class derived from this:

class SomethingFromBase : Base 
{
...
};

,并且用户在加载此库后,请求创建 SomethingFromBase (假设我们从cin中获取名称),并且我们不知道 SomethingFromBase (即, do if(inputstr ==SomethingFrombase){...} 有没有办法创建一个SomethingFromBase的实例?

and, the user, once this library is loaded, asks to create an instance of SomethingFromBase (let's say we get the name from cin.), and, we have no knowledge of SomethingFromBase (i.e, no way to just do if(inputstr == "SomethingFrombase") { ... } is there any way to create an instance of SomethingFromBase?

我相当确定这在(标准)C ++中是不可能的,但我总是希望SO会让我惊喜。

I'm fairly certain this is impossible in (standard) C++, but, I'm always hoping SO will surprise me!

如果这是可能的添加一些库,我还是想知道它。
谢谢!

If this is possible with the addition of some library, I'd still like to know about it. Thanks!

编辑:参见cdhowie的回答。实施此技术的指南:
http://www.linuxjournal.com / article / 3687?page = 0,1
http://www.abstract.net/ViewArticle.aspx?articleID=67

See cdhowie's answer. Guides to implementing this technique: http://www.linuxjournal.com/article/3687?page=0,1 http://www.abstraction.net/ViewArticle.aspx?articleID=67

推荐答案

通常需要通过插件库定义结构类型的一些全局变量来实现这一点,该类型包含可以调用的各种函数的指针。 (如设置,拆卸等)在设置功能期间,他们将回调到您的应用程序中的一些注册函数,他们可以传递一个字符串表示类的名称,以及一个工厂函数指针,将创建一个

You typically achieve this by required that plugin libraries define some global variable of a struct type that contains pointers to various functions you can call. (Like setup, teardown, etc.) During the setup function, they would call back into your application to some "register" function where they could pass in a string representing the name of the class, and a factory function pointer that will create an instance when executed.

您在某些地图中将其隐藏,而当用户输入字符串时,您可以查看地图以查看是否有注册的工厂函数。如果是,只需调用它。

You stash this away in some map, and when the user enters a string, you look at the map to see if there is a factory function registered. If so, just call it.

所以这不是真反射,但你可以手动黑客它在一定程度上。例如,参见Pidgin,其允许规定可能在协议列表中提供许多条目的协议插件。

So this is not "true" reflection, but you can manually hack it to some degree. See, for example, Pidgin, which allows the specification of protocol plugins that may supply many entries in the protocol list.

编辑: 这里是一个很好的指南来实现类似的东西。我更多是一个C人,所以我不能保证它是真正的真棒或任何东西,但乍一看看起来不错。我在Linux上用C做了类似的东西,基本方法工作得很好。

Here is a nifty guide to implementing something similar. I'm more of a C person, so I can't vouch for it being truly awesome or anything, but at first glance it looks good. I've done similar stuff in C on Linux, and the basic approach works pretty well.

这篇关于从其名称的字符串生成派生类实例。 (即反射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆