帮忙看一个函数指针的问题

xie6723632 2013-04-08 06:27:13

typedef struct
{
int c;
int d;
int e;
}UNI;
typedef int (*fun1)(int a,int b);
typedef int (*fun2)(UNI in);
void register_callback(fun1 f1_callback)
{
//要求1. 调用register_callback_hw
//要求2. 最终callback会调到print函数实现打印,实现和register_callback_hw同样
//功能
//要求3. 不能使用全局变量
}


void register_callback_hw(fun2 f2_callback)
{
UNI in;
in.c = 3;
in.d = 2;
f2_callback(in);
}

int print_struct(UNI in)
{
printf("a= %d b= %d a*b= %d\n",in.c,in.d,(in.c) * (in.d));
}

int print(int a,int b)
{
printf("a= %d b= %d a*b= %d\n",a,b,a*b);
return 0;
}

int main()
{
register_callback_hw(print_struct);
system("pause");
}
...全文
73 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xie6723632 2013-04-08
  • 打赏
  • 举报
回复
引用 1 楼 onejian 的回复:
C/C++ code ? 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 #include <iostream> using namespace std; typedef struct{ int c; ……
这种转换对这个是可以,这个是工作中的问题,我是举个例子。直接转对这个是可以的,而事实上fun1和fun2可能是顺序不同,结构不同的函数指针,这样行吗?
onejian 2013-04-08
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;
typedef struct
{     
        int c;     
        int d;     
        int e; 
}UNI; 

typedef int (*fun1)(int a,int b); 
typedef int (*fun2)(UNI in);  

int print(int a,int b)
{
	printf("print: a= %d b= %d a*b= %d\n",a,b,a*b);
    return 0;    
}

void register_callback_hw(fun2 f2_callback)
{
     UNI in;
     in.c = 3;
     in.d = 2;
     f2_callback(in);   
}

void register_callback(fun1 f1_callback)
{
     //要求1. 调用register_callback_hw
     //要求2.  最终callback会调到print函数实现打印,实现和register_callback_hw同样
     //功能 
     //要求3.  不能使用全局变量 
	fun2 tmp = (fun2)f1_callback;
	register_callback_hw(tmp);
}
    

int print_struct(UNI in)
{
	printf("print_struct:a= %d b= %d a*b= %d\n",in.c,in.d,(in.c) * (in.d));
	return 0;
}
 
int main()
{
    register_callback_hw(print_struct);
    register_callback(print);
    system("pause"); 
}
理解函数指针强转,看汇编,call的时候, 少push一个形参

64,690

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧