订阅发布C 回调函数 带参数

本文通过一个简单的C语言程序实例,展示了如何使用回调函数实现订阅端与上报端的数据交互过程。订阅端注册了一个回调函数,该函数在被调用时打印消息并返回修改后的参数值;上报端则触发回调函数的执行,并接收返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

订阅数据端:
main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "test.h"


//定义回调函数
int PrintfText(int a)
{
    printf("Hello World!\n");
    printf("Hello World!%d\n",a);
    return a*10;
}

//实现函数回调
int main(int argc,char* argv[])
{

    appRegisted(PrintfText);//将回调函数注册到发布端
    int ret;
    ret = keypoll();//这里触发执行,也可以主动上报。ret即可有值。
    system("pause");
    return 0;
}

上报数据端:
test.c


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "test.h"

callfuction m_pCallback;

void appRegisted(callfuction pf)//订阅端将回调函数注册过来
{
    m_pCallback = pf;
}

int keypoll(){
    int re;
    re = m_pCallback(5);
    return re;
    
}

test.h
#pragma once
#include<iostream>
using namespace std;

typedef int (*callfuction)(int);

void appRegisted(callfuction pf);

int keypoll();

执行结果:
发布端发布了数据为5,ret为50
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值