如何在 C/C++ 中将 typedef 函数作为参数传递
How to pass a typedef function as a parameter in C/C++
我已经在网上四处寻找了一段时间,但我没有找到任何与我的问题完全相同的东西。我正在使用一个定义了这个东西的类:
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;
}
它现在似乎接受了它。
相关文章:
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- typedef 别名的析构函数
- 类中的 Typedef 函数
- 显式调用 typedef'd 类类型的析构函数的正式正确方法
- 为什么一次包装 typedef 函数签名与原始签名不匹配
- C++:显式调用模板参数的 typedef 的析构函数
- C++ typedef 函数指针,并在一个语句中声明一个指针
- 指向具有 2 个参数的 WINAPI 函数的 Typedef 指针
- 将一个 typedef 函数指向另一个类中的另一个函数
- 返回没有 typedef 的成员函数指针的语法是什么?
- Typedef 函数与函数指针
- typedef 类型不匹配,将其传递到函数中
- 如何使用函数签名的 typedef 作为 std::function 的类型参数
- 我可以在函数定义中使用函数typedef吗
- C++OOP注册回调函数(typedef问题)
- 将__this调用传递给函数typedef
- std::函数typedef中的参数名
- 可以将任何指针类型或基类传递到函数typedef中吗?