使C ++应用程序可脚本化 [英] Making a C++ app scriptable

查看:228
本文介绍了使C ++应用程序可脚本化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有几个函数看起来像这样:

I have several functions in my program that look like this:

void foo(int x, int y)

现在我想让我的程序接受一个类似下面的字符串:

Now I want my program to take a string that looks like:

foo(3, 5)

执行相应的功能。

当我说直接的时候,我的意思是可以扩展和优雅,但它不应该花太长的时间来编码。

When I say straightforward, I mean reasonably extensible and elegant, but it shouldn't take too long to code up.

编辑

使用真正的脚本语言当然会解决我的问题,我仍然想知道是否有一个快速的方式来实现这在纯C ++。

While using a real scripting language would of course solve my problem, I'd still like to know if there is a quick way to implement this in pure C++.

推荐答案

我也去为脚本语言答案。

I'd also go for the scripting language answer.

使用pure C ++,我可能会使用解析器生成器,它将获得令牌和语法规则,并且将给我完全可以解析给定函数的C代码调用语言,并为我提供了该调用的语法树。 flex 可用于对输入进行标记化,而< a href =http://www.gnu.org/software/bison/ =nofollow> bison 可用于解析令牌并将它们转换为语法树。或者,对于该方法,提升精神可以用于解析函数调用语言。我从来没有使用过任何这些工具,而是使用它们的程序,因此我有点知道我会用什么来解决这个问题。

Using pure C++, i would probably use a parser generator, which will will get the token and grammar rules, and will give me C code that exactly can parse the given function call language, and provides me with an syntax tree of that call. flex can be used to tokenize an input, and bison can be used to parse the tokens and transform them into an syntax tree. Alternatively to that approach, Boost Spirit can be used to parse the function call language too. I have never used any of these tools, but have worked on programs that use them, thus i somewhat know what i would use in case i had to solve that problem.

对于非常简单的情况,您可以将语法更改为:

For very simple cases, you could change your syntax to this:

func_name arg1, arg2

然后您可以使用:

std::istringstream str(line);
std::string fun_name; str >> fun_name;
map[fun_name](tokenize_args(str));

地图将是

std::map<std::string, boost::function<void(std::vector<std::string>)> > map;

这将在程序开始时填充函数。 tokenize_args 只是分隔参数,并将它们的向量作为字符串返回。当然,这是非常原始的,但我认为这是合理的,如果你想要的是一些方法来调用一个函数(当然,如果你想真正的脚本支持,这种方法是不够的)。

Which would be populated with the functions at the start of your program. tokenize_args would just separate the arguments, and return a vector of them as strings. Of course, this is very primitive, but i think it's reasonable if all you want is some way to call a function (of course, if you want really script support, this approach won't suffice).

这篇关于使C ++应用程序可脚本化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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