简体   繁体   English

如何在C中使用typedef函数指针调用宏?

[英]How to call a macro with a typedef function pointer in C?

Here, I have a typedef for a function pointer and then I also have a macro that points to the address 0x1234 that is of type "fptr".在这里,我有一个函数指针的 typedef,然后我还有一个指向地址 0x1234 的宏,该地址类型为“fptr”。 But I would like to know how can that macro be called with the arguments to call the resulting function?但是我想知道如何使用参数调用该宏以调用结果函数? Thank you for your help.谢谢您的帮助。

 #include <stdio.h>
    
    typedef void (*fptr)(int, int);

   // 0x1234 will be the address where the reference to fptr will exist
   #define FPTR_MACRO ((fptr)0x1234) 
    
    void main(void){
       
      //How should I call the FPTR_MACRO with the arguments to call that function?
      //FPTR_MACRO(1,1);
    }

If you insist on using macro as is, it would be如果你坚持按原样使用宏,那就是

(*FPTR_MACRO)(1, 1);

But it would be easier to use if rewritten as但是如果改写为会更容易使用

#define FPTR_CALL(x, y) ((*(fptr)0x1234)(x, y))

And than used as并且比用作

FPTR_CALL(1, 1);

Given #define FPTR_MACRO ((fptr)0x1234) , you can call the function with FPTR_MACRO(1, 1) .给定#define FPTR_MACRO ((fptr)0x1234) ,您可以使用FPTR_MACRO(1, 1)调用该函数。

However, this will only work if 0x1234 is a correct address for the function.但是,这仅在 0x1234 是该函数的正确地址时才有效。 If that is not actually the address of the function, but rather is “the address where the reference to fptr will exist”, meaning that 0x1234 is the address where a pointer to the function is, then the macro is incorrect.如果这实际上不是函数的地址,而是“将存在对 fptr 的引用的地址”,这意味着 0x1234 是指向函数的指针所在的地址,那么宏是不正确的。 Instead, you need to get the pointer from the location, as with * (fptr **) 0x1234 , and then you can call the function using that pointer, as with (* (fptr **) 0x1234) (1, 1) .相反,您需要从该位置获取指针,如* (fptr **) 0x1234 ,然后您可以使用该指针调用函数,如(* (fptr **) 0x1234) (1, 1)

Note that the expression used to call a function is a pointer, not a function.请注意,用于调用函数的表达式指针,而不是函数。 When we have f(x, y) , the operand f should actually be a pointer to a function, not a function, per C 2018 6.5.2.2 1. When we do write a function name there, such as pow(x, y) , the function is automatically converted to a pointer, as if we had written (&pow)(x, y) .当我们有f(x, y) ,操作数f实际上应该是一个指向函数的指针,而不是一个函数,根据 C 2018 6.5.2.2 1. 当我们在那里写一个函数名时,例如pow(x, y) ,函数会自动转换为指针,就像我们写的(&pow)(x, y) This is what allows us to write function calls “naturally.”这就是让我们能够“自然地”编写函数调用的原因。 What this means is that, when you already have a pointer, such as FPTR_MACRO , you do not need anything special to call the function.这意味着,当您已经有一个指针时,例如FPTR_MACRO ,您不需要任何特殊的东西来调用该函数。 You already have the required pointer, so you can call it with just FPTR_MACRO(1, 1) .您已经拥有所需的指针,因此您可以仅使用FPTR_MACRO(1, 1)调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM