【问题标题】:Function pointer and calling convention函数指针和调用约定
【发布时间】:2011-06-17 08:26:58
【问题描述】:
float __stdcall (*pFunc)(float a, float b) = (float (__stdcall *)(float,float))0x411280;

如何用调用约定声明函数指针?以上给了我一个错误。

【问题讨论】:

  • @James 可能是一个调用约定不能被嵌套声明符遵循

标签: c function function-pointers calling-convention


【解决方案1】:

对于常规函数,您通常可以这样做:

__cdecl const int func();
__cdecl const int (func)();
const __cdecl int func();
const int __cdecl func();
const int (__cdecl func)();
__cdecl const __cdecl int (__cdecl func)();

编译器是否接受所有这些形式是由实现定义的。铿锵有。对我来说,第 5 版最符合语义,因为它是函数的属性,而不仅仅是返回类型。

你可以用__attribute__((cdecl))而不是__cdecl来完成所有这些,它也可以在函数之后使用,不像__cdecl

const int (__cdecl func)() __attribute__((cdecl));

现在,要声明一个常量指针pfunc 指向具有特定调用约定的函数:

__cdecl const int (*const pfunc)();
const __cdecl int (*const pfunc)();
const int __cdecl (*const pfunc)();
const int (__cdecl *const pfunc)();
const int (*const __cdecl pfunc)();
const int (*__cdecl const pfunc)();
__cdecl const __cdecl int (__cdecl *const pfunc)();
const int (*const pfunc)() __attribute__((cdecl));

请注意,const 必须像往常一样位于星号之后。使用双函数指针,指针可以根据调用约定去任何地方,但您必须将它放在相对于const 的正确位置。

同样,它是根据编译器接受的形式定义的实现。 Clang 接受所有形式并将它们正确解释为类型const int (*const)() __attribute__((cdecl))

【讨论】:

    【解决方案2】:

    __fastcall 是优化的(最快的调用约定),但由于未知原因未使用

    试试:

    int (__fastcall *myfunction)(int,float);
    

    【讨论】:

    • 你应该在发帖之前看看这些未知的原因是什么,如果还没有被问到的话,最终会问一个新问题。这个网站应该是关于分享知识,而不是假设。
    【解决方案3】:

    诀窍是将 __stdcall 放在括号内,如下所示:

    float (__stdcall *pFunc)(float a, float b) = (float (__stdcall *)(float,float))0x411280;
    

    当然,建议您改用 typedef,但同样的技巧也适用:

    typedef float (__stdcall *FuncType)(float a, float b);
    

    【讨论】:

    • 如果我错了请纠正我,但我们不想要typedef float (__stdcall *FuncType)(float a, float b)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    相关资源
    最近更新 更多