在 C++ 应用程序中嵌入 Ruby 解释器 [英] Embedding a Ruby interpreter in a C++ app

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

问题描述

我希望使用 Ruby 作为我的游戏引擎的脚本语言.我找到了描述如何从 C++ 代码调用 Ruby 类的常用文章,反之亦然(例如 here) 但我不太明白如何用这种工作方式做我想做的事...

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屋!

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