Callback Functions Tutorial

【信息科学与工程学】计算机科学与自动化-——第十五篇云计算 12 公有云里的“多Region + 多AZ“ 02 运营算法01 算法逐步思考推理思考(含数学方程式、对象、资源、任务、进程/协程/线程及对应的代数、约束、目标函数/传递函数/依赖函数、参数及参数的数值范围及边界条件、逐步推理的数学方程式列表、上下文切换、并发/串行/随机/乱序/顺序)算法逐步思考推理思考(含数学方程式、对象、资源、任务、进程/协程/线程及对应的代数、约束、目标函数/传递函数/依赖函数、参数及参数的数值范围及边界条件、逐步推理的数学方程式列表、上下文切换、并发/串行/随机/乱序/顺序)云厂商提高闲置资源利用率。算法复杂度为O(N),N为实例数量。 阅读详情
Introduction
If you are reading this article, you probably wonder what callback functions are. This article explains what callback functions are, what are they good for, why you should use them, and so forth. However, before learning what callback functions are, you must be familiar with function pointers. If you aren't, consult a C/C++ book or consider reading the following:


The Syntax of C and C++ Function Pointers
Pointers to member functions
Declaring, Assigning, and Using Function Pointers
What Is a Callback Function?
The simple answer to this first question is that a callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.


Why Should You Use Callback Functions?
Because they uncouple the caller from the callee. The caller doesn't care who the callee is; all it knows is that there is a callee with a certain prototype and probably some restriction (for instance, the returned value can be int, but certain values have certain meanings).


If you are wondering how is that useful in practice, imagine that you want to write a library that provides implementation for sorting algorithms (yes, that is pretty classic), such as bubble sort, shell short, shake sort, quick sort, and others. The catch is that you don't want to embed the sorting logic (which of two elements goes first in an array) into your functions, making your library more general to use. You want the client to be responsible to that kind of logic. Or, you want it to be used for various data types (ints, floats, strings, and so on). So, how do you do it? You use function pointers and make callbacks.


A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the application's queue).

Another example from WinAPI functions that use callback mechanism is EnumWindow(), which enumerates all the top-level windows on the screen. EnumWindow()

 iterates over the top-level windows, calling an application-provided function for each window, passing the handler of the window. If the callee returns a value, the iteration continues; otherwise, it stops. EnumWindows() just doesn't care where the callee is and what it does with the handler it passes over. It is only interested in the return value, because based on that it continues its execution or not.


However, callback functions are inherited from C. Thus, in C++, they should be only used for interfacing C code and existing callback interfaces. Except for these situations, you should use virtual methods or functors, not callback functions.


A Simple Implementation Example
Now, follow the example that can be found in the attached files. I have created a dynamic linked library called sort.dll. It exports a type called CompareFunction:


typedef int (__stdcall *CompareFunction)(const byte*, const byte*);

which will be the type of your callback functions. It also exports two methods, called Bubblesort() and Quicksort(), which have the same prototype but provide different behavior by implementing the sorting algorithms with the same name.


void DLLDIR __stdcall Bubblesort(byte* array,
                                 int size,
                                 int elem_size,
                                 CompareFunction cmpFunc);


void DLLDIR __stdcall Quicksort(byte* array,
                                int size,
                                int elem_size,
                                CompareFunction cmpFunc);
These two functions take the following parameters:



byte* array: a pointer to an array of elements (doesn't matter of which type)
int size: the number of elements in the array
int elem_size: the size, in bytes, of an element of the array
CompareFunction cmpFunc: a pointer to a callback function with the prototype listed above
The implementation of these two functions performs a sorting of the array. But, each time there is a need to decide which of two elements goes first, a callback is made to the function whose address was passed as an argument. For the library writer, it doesn't matter where that function is implemented, or how it is implemented. All that matters it is that it takes the address of two elements (that are the two be compared) and it returns one of the following values (this is a contract between the library developers and its clients):


-1: if the first element is lesser and/or should go before the second element (in a sorted array)
0: if the two elements are equal and/or their relative position doesn't matter (each one can go before the other in a sorted array)
1: if the first element is greater and/or should go after the second element (in a sorted array)
With this contract explicitly stated, the implementation of the Bubblesort() function is this (for Quicksort(), which a little bit more complicated, see the attached files).


void DLLDIR __stdcall Bubblesort(byte* array,
                                 int size,
                                 int elem_size,
                                 CompareFunction cmpFunc)
{
   for(int i=0; i < size; i++)
   {
      for(int j=0; j < size-1; j++)
      {
         // make the callback to the comparison function
         if(1 == (*cmpFunc)(array+j*elem_size,
                  array+(j+1)*elem_size))
         {
            // the two compared elements must be interchanged
            byte* temp = new byte[elem_size];
            memcpy(temp, array+j*elem_size, elem_size);
            memcpy(array+j*elem_size,
                   array+(j+1)*elem_size,
                   elem_size);
            memcpy(array+(j+1)*elem_size, temp, elem_size);
            delete [] temp;
         }
      }
   }
}

Note: Because the implementation uses memcpy(), these library functions should not be used for types other than POD (Plain-Old-Data).
On the client side, there must be a callback function whose address is to be passed to the Bubblesort() function. As a simple example, I have written a function that compares two integer values and one that compares two strings:


int __stdcall CompareInts(const byte* velem1, const byte* velem2)
{
   int elem1 = *(int*)velem1;
   int elem2 = *(int*)velem2;


   if(elem1 < elem2)
      return -1;
   if(elem1 > elem2)
      return 1;


   return 0;
}


int __stdcall CompareStrings(const byte* velem1, const byte* velem2)
{
   const char* elem1 = (char*)velem1;
   const char* elem2 = (char*)velem2;


   return strcmp(elem1, elem2);
}

To put all these to a test, I have written this short program. It passes an array with five elements to Bubblesort() or Quicksort() along with the pointer to the callback functions.


int main(int argc, char* argv[])
{
   int i;
   int array[] = {5432, 4321, 3210, 2109, 1098};


   cout << "Before sorting ints with Bubblesort\n";
   for(i=0; i < 5; i++)
      cout << array[i] << '\n';


   Bubblesort((byte*)array, 5, sizeof(array[0]), &CompareInts);


   cout << "After the sorting\n";
   for(i=0; i < 5; i++)
      cout << array[i] << '\n';


   const char str[5][10] = {"estella",
                            "danielle",
                            "crissy",
                            "bo",
                            "angie"};


   cout << "Before sorting strings with Quicksort\n";
   for(i=0; i < 5; i++)
      cout << str[i] << '\n';


   Quicksort((byte*)str, 5, 10, &CompareStrings);


   cout << "After the sorting\n";
   for(i=0; i < 5; i++)
      cout << str[i] << '\n';


   return 0;
}

If I decide that I want the sorting to be done descending (with the biggest element first), all I have to do is to change the callback function code, or provide another that implements the desired logic.


Calling Conventions
In the above code, you can see the word __stdcall in the function's prototype. Because it starts with a double underscore, it is, of course, a compiler-specific extension, more exactly a Microsoft-specific one. Any compiler that supports development of Win32-based applications must support this or an equivalent one. A function that is marked with __stdcall uses the standard calling convention so named because all Win32 API functions (except the few that take variable arguments) use it. Functions that follow the standard calling convention remove the parameters from the stack before they return to the caller. This is the standard convention for Pascal. But in C/C++, the calling convention is that the caller cleans up the stack instead of the called function. To enforce that a function uses the C/C++ calling convention, __cdecl must be used. Variable argument functions use the C/C++ calling convention.


Windows adopted the standard calling convention (Pascal convention) because it reduces the size of the code. This was very important in the early days of Windows, when it ran on systems with 640 KB RAM.


If you don't like the word __stdcall, you can use the CALLBACK macro, defined in windef.h, as


#define CALLBACK    __stdcall
or


#define CALLBACK    PASCAL

where PASCAL is #defined as __stdcall.


You can read more about calling convention here: Calling Convetions in Microsoft Visual C++.


C++ Methods as Callback Functions
Because you probably write in C++, you want your callback function a method of a class. But, if you try this:


class CCallbackTester
{
public:
   int CALLBACK CompareInts(const byte* velem1, const byte* velem2);
};


Bubblesort((byte*)array, 5, sizeof(array[0]),
           &CCallbackTester::CompareInts);

with a MS compiler, you get this compilation error:


error C2664: 'Bubblesort' : cannot convert parameter 4 from 'int (__stdcall CCallbackTester::*)(const unsigned char *,const unsigned char *)' to 'int (__stdcall *)(const unsigned char *,const unsigned char *)' There is no context in which this conversion is possible


That happens because non-static member functions have an additional parameter, pointer this (see this FAQ for more).


That obliges you to make the member function static. If that's not acceptable, you can use several techniques to overcome that. Check the following links to learn more.


How to Implement Callbacks in C and C++
C++ Callback Demo
Callbacks in C++ Using Template Functors
Notices
The attached files contain two projects. SortingDLL is a Win32 DLL project. The sort.dll output library exports the two sorting functions, Bubblesort() and Quicksort(). The second project, SortDemo, is a Win32 Console Application that demonstrates how to use the sort.dll library. The output directory for both projects is Shared directory, where the following files can be found: sort.h, sort.dll, sort.lib, and SortDemo.exe



第十四节《OpenCascade集成Qt》 将 OpenCascade 与 Qt 集成是开发图形界面应用的常见需求。通过将 OpenCascade 的几何建模与 Qt 的图形用户界面(GUI)功能结合,可以创建强大而灵活的 CAD 或建模工具。OpenCascade 提供了与 Qt 的集成接口,允许你在 Qt 应用程序中嵌入 OpenCascade 的视图,执行几何操作,并与用户进行交互。以下是 OpenCascade 与 Qt 集成的详细步骤:首先,确保已安装 OpenCascade 和 Qt。你可以从 OpenCascade 官方网站或通过包管理 阅读详情

相关推荐

Java网页访问报错?手把手教你解决JRE插件缺失和浏览器拦截问题(附详细截图)

本文针对Java网页访问时常见的JRE插件缺失和浏览器拦截问题,提供了详细的诊断与解决方案。文章首先解释了问题根源在于现代浏览器出于安全考虑停止了对Java插件的支持,然后手把手指导用户确认Java安装、在控制面板配置安全站点列表,并针对Chrome、Edge、Firefox等主流浏览器的不同拦截机制给出了具体的应对策略,最后提供了系统性的故障排查清单,帮助用户彻底解决访问障碍。

weixin_29233857的博客 229

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function错误解决

在《oAuth2实战》一书中,作者岁数代码使用了node.js语言来描述。在oAuth中有4种角色:资源拥有者、客户端、授权服务器和受保护资源,资源拥有者就是人,所以每个场景联系都是三个组件,换成node.js即三个js文件,在三个窗口依次启动client.js、authorizationServer.js、protectedResource.js,当启动完以后,首先点击getOAuthToken,拿到令牌以后,点击getProtectedResource报错了,受保护资源端错误如下所示: ...

风雨诗轩的博客 4728

《ARM64体系结构编程与实践》学习笔记(八)

这是一篇关于《ARM64体系结构编程与实践》的学习笔记,主要内容为:IOMMU和AMBA总线。

2301_76355687的博客 1943

关于TypeError [ERR_INVALID_CALLBACK]: Callback must be a function错误记录

运行npm run dev时,报出如下错误,记录一下: 报出这个错误:这是我webpack.dev.config.js这个配置文件写错了,修改为: 解决方式:fs.open方法中,改成这样: fs.write(fd, buf, 0, 'utf-8', function(err, written, buffer) {}); 参考文档:http://nodejs.cn/api/fs.ht...

gyp0307的博客 1万+

项目回顾一:《高速多端口共享缓存模块》

本帖子仅为了回顾一下一年前自己动手完成的第一个数字ic设计项目的历程,为复试做一下准备,完成的这个sramc模块花了整整四个月的时间,从0到12个模块的代码产出以及模块的验证,虽然没有拿奖,也没有进入复赛,设计过程中使用的技术手段和算法也不太成熟,但这这是一个值得记录的过程!

weixin_60261760的博客 1269

睿抗机器人魔力元宝在完成任务过程中如何使机械臂先到达白色盒子上方而不是先到达工作台?

🏆 本文收录于《全栈Bug调优(实战版)》专栏,致力于分享我在项目实战过程中遇到的各类Bug及其原因,并提供切实有效的解决方案。无论你是初学者还是经验丰富的开发者,本文将为你指引出一条更高效的Bug修复之路,助你早日登顶,迈向财富自由的梦想🚀!同时,欢迎大家关注、收藏、订阅本专栏,更多精彩内容正在持续更新中。让我们一起进步,Up!Up!Up!    备注: 部分问题/难题源自互联网,经过精心筛选和整理,结合数位十多年大厂实战经验资深大佬经验总结所得,数条可行方案供所需之人参考。

**My Coding Family** 1386

Programs as Data: Function Pointers(函数指针)

原文链接:http://www.cprogramming.com/tutorial/function-pointers.html A function pointer is a variable that stores the address of a function tha

masic007のlogs 566

pi-coding-agent 完整详解

pi-coding-agent是一个由Mario Zechner开发的专业AI编程助手,基于Node.js和TypeScript构建。核心功能包括:1)多级思考模式(ThinkingLevel),从none到ultra控制推理深度;2)对话压缩(compaction)管理长对话记忆;3)WebSocket实时通信支持流式交互。该智能体支持代码生成、调试、重构等专业编程任务,采用AI Agent架构,具备工具调用和多轮记忆能力。项目结构通常包含server、agent、config等模块,可通过二次开发扩展功

大坡3D软件开发 2501

node - TypeError: argument handler must be a function 路由报错的原因

原因 : 路由一定要暴露给外部使用 varexpress=require('express') varrouter=express.Router() router.get('/',(req,res)=>{ res.render('main/index.html') }) module.exports=router // 最...

weixin_30819085的博客 1188

【Davinci开发】:CS接口创建及连接

AUTOSAR SWC之间添加CS-port :详细讲解step

2535

乐企归集能力说明文档V2.0006

纳税人销售货物、提供服务开具的增值税发票及购进货物、接受服务取得的增值税发票、海关缴款书(含出口转内销证明)、代扣代缴完税凭证,可以通过本能力进行归集。纳税人可将本能力中的各类规则和接口嵌入本单位信息化系统中(如:销售、报销、财务等),实现发票自动化归集,便于纳税人完成发票入账、抵扣、退税以及代办退税等操作,有效提升涉税业务办理效率。

记录点滴 591

《二十五》Webpack 源码解读

Webpack 代码基于。

花铛 323

手把手教你 Ubuntu 24.04 离线安装 Ollama

本文介绍 Ubuntu 下离线安装 Ollama 并使用 Ollama 部署 llama3.1-70b 大模型

举世誉之而不加劝,举世非之而不加沮,定乎内外之分,辩乎荣辱之境,斯已矣。 1023

回调函数指南(Callback Functions Tutorial)

Author:Marius Bancila http://www.codeguru.com/Cpp/Cpp/cpp_mfc/callbacks/article.php/c10557/翻译by:AllenTing环境:C/C++/VC++ 介绍: 如果你正在读这篇文章,你很可能想知道什么是回调(callback)函数。这篇文章揭示了什么是回调函数,回调函数的好处,为什么你要使用它等等。尽管...

weixin_30664539的博客 125

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

ffmpeg的tutorial中文版学习笔记(四)(新版函数额外补充)

在ffmpeg官方论团中找到的第四篇教程中,在decode_thread函数中多了些一些没见过的函数,现在补充如下: 1:struct AVIOInterruptCB: 头文件:#include avio.h>   成员变量: int(*  callback )(void *)   void *  opaque

坤哥的学习笔记 1123

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Jest 实践指南:测试驱动开发(TDD)实战教程,提升代码质量

想要写出高质量的前端代码,Jest 测试驱动开发(TDD)是你的终极武器!🃏 这本《Jest 实践指南》为你提供一套完整的实战教程,通过测试驱动开发方法,帮助你快速提升代码质量和开发效率。无论你是前端新手还是资深开发者,都能从中掌握实用的 Jest 测试技巧,告别繁琐的调试,拥抱高效的开发流程。 ## 什么是测试驱动开发(TDD)? 测试驱动开发是一种革命性的开发模式,它彻底改变了传统的编程

gitblog_00348的博客 761

LangChain 1.3实战:从零构建具备工具调用与记忆的智能体

大语言模型(LLM)在理解和生成自然语言方面展现出强大能力,但其原生API调用通常局限于简单的文本交互。为了突破这一限制,开发者需要构建能够自主规划、调用外部工具并处理复杂逻辑的智能体(Agent)。这涉及到提示词工程、工具调用、状态管理等一系列工程化挑战。LangChain框架应运而生,它通过标准化的组件和抽象层,将LLM与外部工具、数据源和记忆系统高效集成,极大地简化了智能体应用的开发流程。本文以LangChain 1.3版本为基础,详细演示了如何初始化模型、定义工具、创建智能体执行器并构建完整工作流,

congjukun0600的博客 421

双机双卡RDMA分布式训练yolov5(yolov5+pytorch+DDP+NCCL+RDMA全栈解析)

双机双卡RDMA分布式训练yolov5(yolov5+pytorch+DDP+NCCL+RDMA全栈解析)

Hello Mr.Z的博客 222

基于YOLO的行人车辆目标检测:从YOLOv5到YOLOv8的全栈实战指南

本文全面介绍了基于YOLO系列模型的行人车辆检测系统构建方法。主要内容包括: YOLO算法原理深度解析 详细讲解了YOLOv1-v8各版本的演进历程和核心创新点 对比分析了不同版本的性能特点和适用场景 完整实践指南 数据集准备与标注转换 模型训练调优全流程 验证评估指标解读 模型导出与部署方案 系统实现 提供可运行的核心代码(train.py/val.py/detect.py等) 基于PyQt5的GUI界面开发 性能优化技巧(FP16/量化/剪枝等) 对比实验 在相同数据集上测试YOLOv5-v8的表现 给

m0_51689679的博客 715

启动vue项目时报TypeError [ERR_INVALID_CALLBACK]: Callback must be a function解决

1:今天想要修改我的vue项目中的一些小问题,但是当我把vue项目冲服务器上拉取下来后,执行npm run dev时发现报错了,无法启动vue项目 将错误定位到webpack.dev.config.js文件的12行 发现时fs.write函数的位置,查询fs.write函数参数发现 错误无法对上,这时候修改我的fs.write函数: fs.write(fd, buf, 0, ...

huaweichenai的博客 3641

nodejs中关于回调函数的应用遇到callback is not a function的解决方法

最近在学习nodejs这个服务端开发平台的知识点。一边根据文档学习,一边在写几行测试代码实现有助于了解,在学到回调函数的时候却遇到了callback is not a function的问题。按理说我按照文档代码写的,应该不会出错的,下面是我一开始的时候的代码单纯为了看效果: function doSomething(args, callback) { somethingComplicat...

liangwenli_的博客 3万+

常见问题解答页面列表---收缩展开,引用头部

为收缩效果的管家代码,橘黄色为引用头部的关键代码html页面代码:

jiangshan0318的专栏 2017

回调函数

回调函数 当一个函数A作为参数传给另一个函数B,在函数B中被执行,这个函数A叫做回调函数 function fn(a){ var num = 999; a(num); } fn(function(n){ console.log(n); //999 }) ...

Start_t的博客 194

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function webpack启动报错

#ztj_04 TypeError [ERR_INVALID_CALLBACK]: Callback must be a function 今天启动web项目时突然报错 &amp;amp;gt; webpack --progress --config webpack.dev.config.js 0% compilingfs.js:129 throw new ERR_INVALID_CALLBACK();...

github_39319229的博客 3229
上一篇: A simple exmaple of CallBack function in C
下一篇: c语言静态变量和静态函数
nullpointer
博客等级 码龄15年 14粉丝 36原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值