I have implemented Ruby C extension(i.e. Invoking C function from ruby script) Following is the variable argument function implemented in C from file “cImplementation.c”
#include<stdio.h>
static VALUE cFunction(VALUE self, VALUE exp, const char* fmt, ...)
{
//1st Trial to get expected output
char buff[256];
va_list args;
va_start(args, fmt);
if(vsnprintf(buf, sizeof(buff), fmt, args) > 0)
fputs(buff, stderr);
va_end(args);
// 2nd Trial to get expected output
va_list args;
char buf[1024];
va_start(args,fmt);
vsnprintf(buf, 1024, fmt, args);
printf("String :: %s", buf);
va_end(args);
return Qnil;
}
void Init_MyRuby()
{
VALUE MRuby = rb_define_module("MyRuby");
rb_define_singleton_method(MRuby, "cFunction", cFunction, 1);
}
Following is the code of ruby script that invokes cFuncton() method by pssing printf formated string as below:
require 'cFile'
MyRuby::cFunction(expObject, "My Message:: %s, My Value:: %d", "Hi Im here", 100 )
with above trial 1st we dont get any out put while with the trial 2nd we get emplty string. So can any one suggest how to resolve above problem and get expected output as below:
My Message:: Hi Im here, My Value:: 100.
Thanks in advance.
You should use rb_scan_args to get the function arguments. They can’t be passed directly to vsnprintf.
Maybe try following the example here: http://www.eqqon.com/index.php/Ruby_C_Extension_API_Documentation_(Ruby_1.8)