c - 如何使用 c 扩展扩展我的 ruby​​ 类?

标签 c ruby inline ruby-c-extension

如果我有用 Ruby 编写的 Foo::Bar,并且我想向 Bar 添加一个方法作为 C 扩展。现在,当我像这样在 C 中创建 Foo::Bar 时:

static VALUE Foo;
static VALUE Bar;

static VALUE 
print_string(VALUE self, VALUE string) {
  printf("%s", StringValuePtr(string));
  return Qnil;
}

void Init_foo() {
    Foo = rb_define_module("Foo");
    Bar = rb_define_class_under(Foo, "Bar", rb_cObject);
    rb_define_method(Bar, "print_string", print_string, 1);
}

但问题是:

ruby-1.9.2-p180 :001 > require 'ext/foo'   #=> ["Foo"]
ruby-1.9.2-p180 :002 > f = Foo::Bar.new   #=> #<Foo::Bar:0x000001046bce48>
ruby-1.9.2-p180 :003 > f.original_ruby_method
NoMethodError: undefined method `original_ruby_method' for #<Foo::Bar:0x000001046bce48>

所以我本质上是覆盖原来的 Foo::Bar。如何扩展它而不覆盖它?

最佳答案

我找到了解决这个问题的方法。

void Init_foo() {
    rb_eval_string("require './lib/foo'");
    VALUE Bar = rb_path2class("Foo::Bar");
    rb_define_method(Bar, "print_string", print_string, 1);
}

关于c - 如何使用 c 扩展扩展我的 ruby​​ 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442920/

相关文章:

c++ - 如果在 C++ 中没有先前声明的情况下定义自由函数,是否会隐式内联?

CKEDITOR 内联编辑器工具栏上的文本选择

python - 我如何获得图像识别的概率

arrays - ruby ,传统知识库。 getopenfile 的输出

ruby-on-rails - decent_exposure 每次创建双条目

ruby-on-rails - rails 中的路径解析

c# - 如何使用内联条件 C# 获取数组的某些元素?

c - 初始化程序元素不是常量 - 在循环内使用静态变量

c - 为什么我们不能在 Linux 中通过 system() 系统调用更改目录?

c++ - 如何使用字符串的字符指针?