[英]how to resolve errors with the use of va_list?
我已經實現了Ruby C擴展(即從ruby腳本調用C函數)以下是從文件“ cImplementation.c”在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);
}
以下是ruby腳本的代碼,該腳本通過pssing printf格式化的字符串來調用cFuncton()方法,如下所示:
require 'cFile'
MyRuby::cFunction(expObject, "My Message:: %s, My Value:: %d", "Hi Im here", 100 )
在上面的第一個試驗中,我們沒有任何輸出,而在第二個試驗中,我們得到了示例字符串。 因此,任何人都可以建議如何解決上述問題並獲得預期的輸出,如下所示:我的消息::我很高興,我的價值::100。在此先感謝。
您應該使用rb_scan_args來獲取函數參數。 它們不能直接傳遞給vsnprintf。
也許嘗試在此處遵循以下示例: http : //www.eqqon.com/index.php/Ruby_C_Extension_API_Documentation_(Ruby_1.8)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.