How to wrap a function with variable length arguments?

I am aiming to do this in C/C+npls.

I found Variable Length Arguments yet this recommends a remedy with Python & C making use of libffi.

Currently, if I intend to cover printf function with myprintf

What I do resembles listed below:

void myprintf(char* fmt, ...)
{
    va_list args;
    va_start(args,fmt);
    printf(fmt,args);
    va_end(args);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 9;
    int b = 10;
    char v = 'C';
    myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n",a, v, b);
    return 0;
}

But the outcomes are not as anticipated!

This is a number: 1244780 and
this is a character: h and
another number: 29953463

Any factor where did I miss out on ??

50
2022-06-07 15:16:07
Source Share
Answers: 4

the trouble is that you can not make use of 'printf' with va_args. You have to make use of vprintf if you are making use of variable argument checklists. vprint, vsprintf, vfprintf, etc (there are additionally 'secure' variations in Microsoft is C runtime that will certainly protect against barrier overruns, etc)

You example functions as adheres to:

void myprintf(char* fmt, ...)
{
    va_list args;
    va_start(args,fmt);
    vprintf(fmt,args);
    va_end(args);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 9;
    int b = 10;
    char v = 'C'; 
    myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n",a, v, b);
    return 0;
}
68
2022-06-07 17:11:58
Source

How do you suggest a pure C/C+npls remedy?

The remainder parameter () is sustained cross system in the C runtime.

http://msdn.microsoft.com/en-us/library/kb57fad8.aspx

1
2022-06-07 15:42:30
Source

Are you making use of C or C+npls? The next C+npls variation, C+npls 0x, will certainly sustain variadic templates which give a remedy to that trouble.

An additional workaround can be attained by brilliant driver straining to attain a syntax similar to this:

void f(varargs va) {
    BOOST_FOREACH(varargs::iterator i, va)
        cout << *i << " ";
}

f(args = 1, 2, 3, "Hello");

In order to get this to function, the class varargs needs to be applied to bypass operator = that returns a proxy object which, subsequently, bypasses operator ,. Nonetheless, making this alternative type secure in existing C+npls isn't feasible regarding I recognize given that it would certainly need to function by type erasure.

3
2022-06-07 15:42:14
Source

I am additionally unclear what you suggest by pure

In C+npls we make use of

#include <cstdarg>
#include <cstdio>

class Foo
{   void Write(const char* pMsg, ...);
};

void Foo::Write( const char* pMsg, ...)
{
    char buffer[4096];
    std::va_list arg;
    va_start(arg, pMsg);
    std::vsnprintf(buffer, 4096, pMsg, arg);
    va_end(arg);
    ...
}
8
2022-06-07 15:39:08
Source