如何在 C/C++ 中将 typedef 函数作为参数传递

How to pass a typedef function as a parameter in C/C++

本文关键字:函数 typedef 参数传递 中将 C++      更新时间:2023-10-16

我已经在网上四处寻找了一段时间,但我没有找到任何与我的问题完全相同的东西。我正在使用一个定义了这个东西的类:

typedef bool ProgressCallback(double progress);

然后有一个函数像这样使用它:

// The documentation says that it will call progress_callback()
// during the write where the progress parameter = percentage complete
void WriteToFile(char* filename, ProgressCallback* progress_callback)

我到底应该如何调用这个函数?主要是 typedef 语法让我失望,因为将函数作为参数传递通常并不难。这是我尝试过的:

// Apparently I can't just say "Progress Callback MyCallback{}"
// Since it gives me "function type may not come from a typedef" error
bool MyCallbackFunction(double progress){
return true;
}
void OtherFunction(){
// Can't assign. I get "a value type of bool (*)(double progress)" cannot be
// used to initalize an entity of type ProgressCallback*" error.
ProgressCallback* myfunction = MyCallbackFunction;
WriteToFile("Test.txt", myfunction);
}

显然我知道我这样做不正确。但这是我得到的最接近的。我完全不知道我应该如何将该参数传递给 WriteToFile()。

任何帮助将不胜感激!

使用

typedef bool (*ProgressCallback)(double progress);

定义ProgressCallback

然后,您可以使用

ProgressCallback myfunction = MyCallbackFunction;
WriteToFile("Test.txt", myfunction);

解决了!我需要显式声明一个调用约定来执行此操作。所以我改变了:

bool MyCallbackFunction(double progress){
return true;
}

bool __stdcall MyCallbackFunction(double progress){
return true;
}

它现在似乎接受了它。