8

次の 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);
}

基本的には、可変引数を持つ関数を「ジェネリック」関数ポインターに格納するという考え方です。比較として、固定引数リストを持つ別の関数も含めました。これを x86 Linux、amd64 Linux、Win32、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

Win64 では動的関数が可変引数リストからゼロ値を取得するのに、他の構成では取得しないのはなぜですか? このようなものは合法ですか?コンパイラが文句を言わなかったからだと思いました。

4

2 に答える 2

10

あなたのコードは無効です。可変個引数関数を呼び出すには、それが可変個引数であることを示すプロトタイプが必要ですが、使用している関数ポインター型ではこれが提供されません。呼び出しが未定義の動作を呼び出さないようにするには、次のdynamic_funcようにポインターをキャストして呼び出しを行う必要があります。

((void (*)(void *, ...))dynamic_func)(NULL, x);
于 2011-09-05T13:26:14.777 に答える
4

必要がなくても varargs を使用することを意味する場合でも、一貫した関数定義で作業する必要があります。最善の方法は、必要に応じて詳細にすることです。

...

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);
}
于 2011-09-05T13:09:42.830 に答える