Ruby C API字符串和符号相等?

时间:2021-11-17 20:45:57

Writing a C extension for a Ruby gem, I need to test a parameter value for equality with a known symbol and string.

为Ruby gem编写一个C扩展,我需要测试一个与已知符号和字符串相等的参数值。

I realize you can intern a string with

我知道你可以和我一起实习

char *foo = "foo";
VALUE foo_string_value = rb_intern(foo);

and then convert it into a symbol:

然后把它转换成一个符号:

VALUE foo_sym_value = ID2SYM(foo_string_value);

My question is whether I can now reliably test the parameter, which may be a symbol or string, :foo or 'foo', with these using C pointer equality:

我的问题是现在是否可以可靠地测试参数,它可能是一个符号或字符串:foo或'foo',使用C指针相等:

if (param == foo_string_value || param == foo_sym_value) {
  ...
}

In other words, does the interning guarantee that pointer equality is also value equality for symbols and strings?

换句话说,插入是否能保证指针相等对符号和字符串来说也是值相等?

If this is the wrong approach, then what's the right one to do this comparison?

如果这是一种错误的方法,那么做这种比较的正确方法是什么呢?

1 个解决方案

#1


3  

I figured this out. A reasonable way to do what I want appears to be

我想这一点。一种合理的方式去做我想做的事

VALUE square_sym = ID2SYM(rb_intern("square"));
VALUE kind_as_sym = rb_funcall(kind_value, rb_intern("to_sym"), 0);
if (square_sym == kind_as_sym) {
  ...
}

Symbols are always interned and have unique values. Strings aren't and don't. They can be interned to get IDs that are integers unique for each string, but that doesn't help in this case.

符号总是被嵌入并且有独特的价值。字符串不,不要。它们可以被代入以获得每个字符串唯一的整数id,但在这种情况下这没有帮助。

#1


3  

I figured this out. A reasonable way to do what I want appears to be

我想这一点。一种合理的方式去做我想做的事

VALUE square_sym = ID2SYM(rb_intern("square"));
VALUE kind_as_sym = rb_funcall(kind_value, rb_intern("to_sym"), 0);
if (square_sym == kind_as_sym) {
  ...
}

Symbols are always interned and have unique values. Strings aren't and don't. They can be interned to get IDs that are integers unique for each string, but that doesn't help in this case.

符号总是被嵌入并且有独特的价值。字符串不,不要。它们可以被代入以获得每个字符串唯一的整数id,但在这种情况下这没有帮助。