Domanda

Sto cercando di farlo in C/C++.

Mi sono imbattuto Argomenti a lunghezza variabile ma questo suggerisce una soluzione con Python e C utilizzando libffi.

Ora, se voglio concludere printf funzionare con myprintf

Quello che faccio è come di seguito:

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;
}

Ma i risultati non sono quelli sperati!

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

Qualche punto in cui mi sono perso??

È stato utile?

Soluzione

il problema è che non puoi usare 'printf' con va_args.Devi usare vprintf se stai usando elenchi di argomenti variabili.vprint, vsprintf, vfprintf, ecc.(esistono anche versioni "sicure" nel runtime C di Microsoft che impediranno il sovraccarico del buffer, ecc.)

Il tuo campione funziona come segue:

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;
}

Altri suggerimenti

In C++11 questa è una possibile soluzione utilizzando Variadic templates:

template<typename... Args>
void myprintf(const char* fmt, Args... args )
{
    std::printf( fmt, args... ) ;
}

MODIFICARE

Come sottolinea @rubenvb, ci sono dei compromessi da considerare, ad esempio genererai codice per ogni istanza che porterà a un ingrossamento del codice.

Inoltre non sono sicuro di cosa intendi per puro

In C++ usiamo

#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);
    ...
}

In realtà, c'è un modo per chiamare una funzione che non ha va_list versione da un involucro.L'idea è quella di utilizzare l'assemblatore, non toccare gli argomenti nello stack e sostituire temporaneamente l'indirizzo di ritorno della funzione.

Esempio per Visual C x86. call addr_printf chiamate printf():

__declspec( thread ) static void* _tls_ret;

static void __stdcall saveret(void *retaddr) {
    _tls_ret = retaddr;
}

static void* __stdcall _getret() {
    return _tls_ret;
}

__declspec(naked)
static void __stdcall restret_and_return_int(int retval) {
    __asm {
        call _getret
        mov [esp], eax   ; /* replace current retaddr with saved */
        mov eax, [esp+4] ; /* retval */
        ret 4
    }
}

static void __stdcall _dbg_printf_beg(const char *fmt, va_list args) {
    printf("calling printf(\"%s\")\n", fmt);
}

static void __stdcall _dbg_printf_end(int ret) {
    printf("printf() returned %d\n", ret);
}

__declspec(naked)
int dbg_printf(const char *fmt, ...)
{
    static const void *addr_printf = printf;
    /* prolog */
    __asm {
        push ebp
        mov  ebp, esp
        sub  esp, __LOCAL_SIZE
        nop
    }
    {
        va_list args;
        va_start(args, fmt);
        _dbg_printf_beg(fmt, args);
        va_end(args);
    }
    /* epilog */
    __asm {
        mov  esp, ebp
        pop  ebp
    }
    __asm  {
        call saveret
        call addr_printf
        push eax
        push eax
        call _dbg_printf_end
        call restret_and_return_int
    }
}

Utilizzi C o C++?La prossima versione di C++, C++0x, supporterà modelli variadici che forniscono una soluzione a quel problema.

Un'altra soluzione alternativa può essere ottenuta mediante l'overloading intelligente degli operatori per ottenere una sintassi come questa:

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

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

Per far funzionare tutto questo, il class varargs deve essere implementato per sovrascrivere operator = che restituisce un oggetto proxy che, a sua volta, sovrascrive operator ,.Tuttavia, per quanto ne so, rendere sicuro questo tipo di variante nell'attuale C++ non è possibile poiché dovrebbe funzionare tramite cancellazione del tipo.

Come intendi una soluzione C/C++ pura?

Il parametro rest (...) è supportato su più piattaforme nel runtime C.

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

void myprintf(char* fmt, ...)
{
    va_ list args;
    va_ start(args,fmt);
    printf(fmt,args); ----> This is the fault. vprintf(fmt, args); should have been used.
    va_ end(args);
}
If you're just trying to call printf, 
there's a printf variant called vprintf that takes 
the va_list directly :  vprintf(fmt, args);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top