Domanda

Si consideri il seguente programma C:

#include <stdio.h>
#include <stdarg.h>

typedef void (callptr)();

static void fixed(void *something, double val)
{
    printf("%f\n", val);
}

static void dynamic(void *something, ...)
{
    va_list args;
    va_start(args, something);
    double arg = va_arg(args, double);
    printf("%f\n", arg);
}

int main()
{
    double x = 1337.1337;
    callptr *dynamic_func = (callptr *) &dynamic;
    dynamic_func(NULL, x);
    callptr *fixed_func = (callptr *) &fixed;
    fixed_func(NULL, x);

    printf("%f\n", x);
}

Fondamentalmente, l'idea è di memorizzare una funzione con argomenti variabili in un puntatore alla funzione "generica". A titolo di confronto, ho incluso anche un'altra funzione con lista di argomenti fisso. Ora vediamo cosa succede quando si esegue questo su Linux x86, amd64 Linux, Win32 e Win64:

$ gcc -m32 -o test test.c
$ file test
test: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ./test
1337.133700
1337.133700
1337.133700

$ gcc -o test test.c
$ file test
test: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ./test
1337.133700
1337.133700
1337.133700

C:\>gcc -o test.exe test.c
C:\>file test.exe
test.exe: PE32 executable for MS Windows (console) Intel 80386 32-bit
C:\>test.exe
1337.133700
1337.133700
1337.133700

C:\>x86_64-w64-mingw32-gcc -o test.exe test.c
C:\>file test.exe
test.exe: PE32+ executable for MS Windows (console) Mono/.Net assembly
C:\>test.exe
0.000000
1337.133700
1337.133700

Perché la funzione dinamica ottiene un valore pari a zero dalla lista di argomenti variabili su Win64, ma non su una qualsiasi delle altre configurazioni? È qualcosa di simile anche legale? Ho pensato che è perché il compilatore non si lamentava.

È stato utile?

Soluzione

Your code is not valid. Calling a variadic function requires a prototype indicating that it's variadic, and the function pointer type you're using does not provide this. In order for the call not to invoke undefined behavior, you would have to cast the dynamic_func pointer like this to make the call:

((void (*)(void *, ...))dynamic_func)(NULL, x);

Altri suggerimenti

You should work with consistent function definitions, even if that means to use varargs even if not needed. The best is to be as verbose as needed.

...

typedef void myfunc_t(void *, ...);

...

myfunc_t dynamic;
void dynamic(void * something, ...)
{

...

}

...

int main()
{
    double x = 1337.1337;
    myfunc_t *callnow;
    callnow = &dynamic;
    callnow(NULL, x);

    printf("%f\n", x);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top