How to get all arguments from following function in c/c++?

孤街醉人 提交于 2019-12-04 07:12:11

问题


following is the implementation of my method

static VALUE myMethod(VALUE self, VALUE exc, const char* fmt, ...) { 
   // Need to get all the arguments passed to this function and print it 
}

function is called as follows:

myMethod(exception, ""Exception message: %s, Exception object %d",
          "Hi from Exception", 100);

Can you provide the code for myMethod() that will access all the arguments and print them out.

Thanks in advance.


回答1:


The va_start and va_arg macro's are used to get the variable arguments in a function. An example can be found on the Microsoft site: http://msdn.microsoft.com/en-us/library/kb57fad8(v=vs.71).aspx

In your case it's a bit trickier, since you need to parse the format string to exactly know how many arguments should be given and of which type they are. Luckily, the CRT contains a function for that. The vfprintf function can be given a va_list (which you get from va_start). vfprintf will use this one to process all the extra arguments. See http://www.cplusplus.com/reference/clibrary/cstdio/vfprintf/ for an example.




回答2:


One way is to use vsnprintf().

Sample code:

char buf[256];
va_list args;

va_start(args, fmt);

if(vsnprintf(buf, sizeof(buf), fmt, args) > 0)
  fputs(buf, stderr);

va_end(args);



回答3:


You need to use va_start and va_arg macros to get the arguments. You can take a look at this - it has some examples.

http://www.go4expert.com/forums/showthread.php?t=17592



来源:https://stackoverflow.com/questions/7426724/how-to-get-all-arguments-from-following-function-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!