我已经开始为clang-c库编写一个ruby模块。
我在我的clang c模块中包装
unsigned clang_visitChildren(CXCursor parent,
CXCursorVisitor visitor,
CXClientData client_data);
有这样的访问者:
typedef enum CXChildVisitResult (*CXCursorVisitor)(CXCursor cursor,
CXCursor parent,
CXClientData client_data);
并且ruby代码(正在运行)看起来像这样:
Clangc.visit_children(cursor: tu.cursor) do |cursor, parent|
puts cursor
puts parent
Clangc::ChildVisitResult::RECURSE
end
我们的想法是获取块,将其作为参数传递给访问者,并在访问者中调用它。
C胶水代码如下所示:
VALUE
m_clangc_visit_children_with_proc(VALUE self, VALUE cursor, VALUE aproc)
{
if (rb_class_of(aproc) != rb_cProc) rb_raise(rb_eTypeError, "Need a block");
VALUE callback = aproc;
Cursor_t *c;
unsigned ret_with_break;
Data_Get_Struct(cursor, Cursor_t, c);
ret_with_break = clang_visitChildren(c->data,
visitor,
(CXClientData) callback);
/*return false if ret_with_break == 0*/
return NOT_0_2_RVAL(ret_with_break);
}
与访问者(回调):
static enum CXChildVisitResult
visitor(CXCursor cursor, CXCursor parent, CXClientData client_data)
{
/*basic variables initialization...*/
r_ret = rb_funcall(callback, rb_intern("call"), 2, r_cursor, r_parent);
if (TYPE(r_ret) == T_FIXNUM)
{
ret = NUM2UINT(r_ret);
if (ret == CXChildVisit_Break || ret == CXChildVisit_Continue ||
ret == CXChildVisit_Recurse)
return ret;
else
return CXChildVisit_Break;
}
else
return CXChildVisit_Break;
}
我的回答是我应该在这里使用rb_protect吗?
代码可以在这里找到:
https://github.com/cedlemo/ruby-clangc/blob/master/ext/clangc/_clangc_functions.c#L146
答案 0 :(得分:0)
经过一些测试并在阅读了其他人的代码后,我得出的结论是rb_protect
用于封装rb_funcall
并非强制性。
当您需要在C中处理由rb_funcall
执行的ruby块或过程中的可能异常时,应该使用它。
我应该提一下,当你在C中嵌入ruby解释器时,处理这些异常比处理一些C ruby扩展时更重要。
参考文献:
git clone git://libvirt.org/ruby-libvirt.git
git clone https://github.com/ruby-gnome2/ruby-gnome2.git
http://clalance.blogspot.fr/2011/01/writing-ruby-extensions-in-c-part-5.html