Using Ruby Blocks from C with SWIG
I am using SWIG to wrap a C interface in Ruby. Given two structs
typedef struct Vertex {
int color, discoverd, finished;
struct Vertex *next;
} Vertex;
typedef struct Graph {
struct Vertex *vertex;
} Graph;
how can I create a #each
method w开发者_运维技巧hich yields the current vertex, so that I can process it in Ruby. Currently my SWIG interface file contains something like
%extend Graph {
void each() {
Vertex *v;
v = self->vertex;
while(v) {
rb_yield(Qnil); // how do I yield a vertex?
v = v->next;
}
}
};
Thanks in advance for your help.
--t6d
One way is convert the vertex to a VALUE with the swig functions. The swig function to wrap the C struct as a ruby/swig object is SWIG_NewPointerObj.
rb_yield(SWIG_NewPointerObj(SWIG_as_voidptr(v), SWIGTYPE_p_Vertex, 0 | 0 ));
SWIG_NewPointerObj/SWIGTYPE_p_* are defined as a macros in the wrapper, so you will need to call the above code from the wrapper (which will happen when you use %extend).
精彩评论