在C ++应用程序中嵌入Ruby解释器 [英] Embedding a Ruby interpreter in a C++ app
问题描述
我希望使用Ruby作为我的游戏引擎的脚本语言。我发现了通常的文章描述如何从C ++代码调用Ruby类,反之亦然(例如这里),但是我不能看到如何做我想要的那种工作方式...
I'm hoping to use Ruby as a scripting language for my game engine. I've found the usual articles describing how to call Ruby classes from C++ code and vice versa (e.g. here) but I can't quite see how to do what I want with that way of working...
我的引擎目前使用一种我用Flex和Bison写的自己的小语言,和一个基于堆栈的虚拟机。脚本不总是从头到尾运行,例如它们有时包括诸如睡眠2秒或等待直到字符已完成走的命令,因此调度器保持对每个脚本的状态和指令的标签指针,并知道什么时候恢复它们,等等。
My engine currently uses a little language I wrote myself with Flex and Bison, and a little stack based virtual machine. Scripts don't always run right through from start to finish, for instance they sometimes includes commands like "sleep for 2 seconds" or "wait until character has finished walking", so the scheduler keeps tabs on the status of each script and an instruction pointer, and knows when to resume them, and so on.
所以看起来我真的需要某种嵌入式Ruby解释器,我可以进行一定程度的控制而不是简单地调用Ruby方法。
So it seems that I really need some kind of embedded Ruby interpreter that I can exercise a certain degree of control over, rather than simply calling Ruby methods. Or am I just being obtuse and missing something?
我在Microsoft Visual C ++中工作,所以理想情况下,任何解决方案都会编译好,而且很容易。
I'm working in Microsoft Visual C++, so ideally any solution would compile nice and easily in that.
推荐答案
以下是包含错误处理的示例。
Here's an example including error handling.
#include <iostream>
#include <ruby.h>
using namespace std;
int main(void)
{
ruby_init();
ruby_init_loadpath();
int status;
rb_load_protect(rb_str_new2("./test.rb"), 0, &status);
if (status) {
VALUE rbError = rb_funcall(rb_gv_get("$!"), rb_intern("message"), 0);
cerr << StringValuePtr(rbError) << endl;
};
ruby_finalize();
return status;
}
这篇关于在C ++应用程序中嵌入Ruby解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!