Pavel Smerk said:
Unfortunately, I definitely need a library which could be easily used
in C programs (or elsewhere). A ruby script does not fit my needs.
Because it is possible to embed Perl interpreter to a C program (man
perlembed,
http://perldoc.perl.org/perlembed.html), I believe there
could be something similar in Ruby.
But unix provides all that is needed to do such a thing.
/* pseudo-code */
typedef struct ruby{
int to_ruby;
int from_ruby;
} ruby;
ruby* init_ruby(){
int to_ruby[2];
int from_ruby[2];
int res=0;
res=pipe(to_ruby); if(res!=0){perror("pipe");exit(1);}
res=pipe(from_ruby); if(res!=0){perror("pipe");exit(1);}
if(0==fork()){
close(to_ruby[0]);
close(from_ruby[1]);
ruby* r=malloc(sizeof(ruby));
r->to_ruby=to_ruby[1];
r->from_ruby=from_ruby[0];
return(r);
}else{
close(to_ruby[0]);
close(from_ruby[1]);
close(0);
close(1);
dup2(to_ruby[1],0);
dup2(from_ruby[0],1);
execl("/usr/bin/irb");
exit(0);
}
}
char* ruby_eval(ruby* r,const char* e){
while(strlen(e)>0){
int wrote=write(r->to_ruby,e,strlen(e));
if(wrote<0){
perror("write to ruby");
exit(1);
}else{
e+=wrote;
}
}
{
int bufsize=65536;
char* buffer=malloc(bufsize);
int readed=read(r->from_ruby,buffer,bufsize-1);
if(readed<0){
/* actually, should check for EAGAIN, etc */
perror("read from ruby");
}
buffer[readed]=0;
return(buffer);
}
}
so now you can write:
ruby* r=init_ruby();
printf("%s\n",ruby_eval(r,"[1,2,3].length;\n")

;
// etc...
You don't need a _library_ for just two routines, I would think...