简体   繁体   English

如何使用宏作为函数指针?

[英]How to use macro as function pointer?

How can I use macros as function pointers? 如何使用宏作为函数指针? I have no idea to solve this. 我不知道要解决这个问题。 I created a sketch (doesn't work, full of syntax errors) to show what I try to accomplish. 我创建了一个草图(无效,充满语法错误)以显示我要完成的工作。 Please help! 请帮忙!

#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
#define D1_OUT(x) (x*1024) //I want to use this for Pin1 calculation

struct Pin {
  CalcMethod *calcMethod; //int methodName(int x) { return MACRO(x); }

  Pin(CalcMethod *calcMethodParam) {
    calcMethod = calcMethodParam;
  }

  int calc(int x) {
    return calcMethod(x);
  }
};

#define PIN_COUNT 2
Pin *pins[PIN_COUNT];

void start() {
    pins[0] = new Pin(D0_OUT); //use the D0_OUT macro to calculate
    pins[1] = new Pin(D1_OUT); //use the D1_OUT macro to calculate
    int pin0CalcResult=pins[0]->calc(5); // =5/1024*100
    int pin1CalcResult=pins[1]->calc(6); // =6*1024
}

Macros are handled by the preprocessor. 宏由预处理器处理。 They don't exist in the compiled code, therefore there is no pointer. 它们在编译后的代码中不存在,因此没有指针。

There is one rule you should follow in modern code and that rule is "don't use macros for furnctions". 现代代码中应遵循一个规则,该规则是“不要使用宏进行分叉”。 Macros for functions are a relict that still has some good uses but they are very rare. 函数宏是一个遗留物,仍然有一些很好的用途,但是非常罕见。

Just declare a normal function 只要声明一个正常的功能

int do_out(int x) {
    return x / 1024 * 100;
}

Also see "static const" vs "#define" vs "enum" 另请参见“静态const”与“ #define”与“枚举”

You can, but not advisable , use macros as named lambdas. 您可以但不建议将宏用作命名为lambdas。 Thus 从而

#define D0_OUT [](int x) { return x / 1024 * 100; }
#define D1_OUT [](auto x) { return x * 1024; }

and it should work. 它应该工作。

D0_OUT example usable in C++11 and D1_OUT usable with C++14. D0_OUT示例可在C ++ 11中使用,而D1_OUT可在C ++ 14中使用。

I know this is an old thread.. 我知道这是一个旧线程。

Assuming that you cannot just change the macro to be a function. 假设您不能仅将宏更改为函数。 Maybe it is part of a driver of library somewhere and you need to pass it into another function for some reason like unit testing. 也许它是某个地方的库驱动程序的一部分,由于某些原因(例如单元测试),您需要将其传递给另一个函数。 You can just wrap the macro within your .c file where you want to use it. 您可以将宏包装在您要使用的.c文件中。

So this: 所以这:

#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation

becomes: 变为:

static int D0_OUT_wrapper(int x)
{
    return D0_OUT(x);
}

So wrapper goes in like normal: 所以包装器像往常一样进入:

pins[0] = new Pin(D0_OUT_wrapper);

If you have full control of the code you are writing then just don't use macros. 如果您完全控制要编写的代码,则不要使用宏。

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

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