23.10.10 学习笔记

今日学习总结:

(1)动态库调用方法 

   分为显式加载和隐式加载 ,本次项目中用到了显式加载。

     实现demo:

typedef void(*AddProc1)(LPBYTE lpSrc, LPBYTE lpDst, LPBYTE lpDst_, int nSrcCount, int nW, int nH);//定义函数指针类型
 
	HINSTANCE hInst;
	AddProc1 Add1 = NULL;
	hInst = LoadLibrary("MyImageProcess.dll");//动态加载Dll
	if (hInst != NULL)
	{
		Add1 = (AddProc1)GetProcAddress(hInst, "WELLNER_MODIFYED");//获取Dll的导出函数
 
		if (!Add1)
		{
			MessageBox("获取Add函数地址失败!");
		}
		Add1(lpSrcBit, lpDstBit, lpDst_Bit, nCount, nW, nH);
 
		//显示图像数据
		m_DstView.SetImgData(lpDstBit, nW, nH, nDstCount);
		m_DstView.Invalidate();
 
		delete[] lpSrcBit;
		delete[] lpDstBit;
		delete[]lpDst_Bit;
		FreeLibrary(hInst);
	}
(2)typedef + 函数指针 (更优雅的使用指针函数)

三种函数指针的声明方法:

int add(int a, int b) {
    return a + b;
}
 
typedef int (PTypeFun1)(int, int); // 声明一个函数类型
typedef int (*PTypeFun2)(int, int); // 声明一个函数指针类型
int (*padd)(int, int); // 传统形式,定义一个函数指针变量
  
int main() {
    PTypeFun1 *pTypeAdd1 = add;
    PTypeFun2 pTypeAdd2 = add;
    padd = add;
    cout << pTypeAdd1(1, 2) << endl;
    cout << pTypeAdd2(1, 2) << endl;
    cout << padd(1, 2) << endl;
    return 0;
}

那么使用 typedef 来定义函数指针有什么好处呢?请看下面。

为什么一定要使用 typedef 定义函数指针呢?

1.使用 typedef 定义函数指针,代码看起来更简洁,也更不容易出错。

2.当函数指针作为其它函数的参数,特别是作为返回值时,直接使用的函数指针无法编译。

如下:

#include <stdio.h>
 
void FunA() {
    printf("call FunA\n");
}
 
void FunB(int n) {
    printf("call FunB. n is : %d\n", n);
}
 
typedef void (*PtrFunA)();
typedef void (*PtrFunB)(int);
 
// 函数指针作为函数参数使用
void usePtrFunA(PtrFunA p) {
    p();
}
 
void usePtrFunB(PtrFunB p, int n) {
    p(n);
}
 
//下面这种语法编译器已经无法识别了
//(void (*PtrFunA)()) getPtrFunA2() {
//    return FunA;
//}
 
// 函数指针作为函数返回值使用 
PtrFunA getPtrFunA() {
    PtrFunA p = FunA;
    return p;
}
 
PtrFunB getPtrFunB() {
    PtrFunB p = FunB;
    return p;
}
 
int main() {
    // 获取 FunA 函数的函数指针
    PtrFunA a = getPtrFunA();
    // 使用 FunA 函数的函数指针
    usePtrFunA(a);
 
    // 获取 FunB 函数的函数指针
    PtrFunB b = getPtrFunB();
    // 使用 FunB 函数的函数指针
    usePtrFunB(b, 1);
    return 0;
}

(在使用的时候 我犯了一个很愚蠢的错误 :我将枚举的结构体名称当作了函数指针的返回值 结果报错 仔细一想 枚举里的数据都是常量 拿到整个枚举没什么用啊,用int拿到其中一个值就好了呀)

(为了方便,直接粘贴了别人的代码,非原创)


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学伟!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值