C语言函数指针实现嵌入式设计模式实战

嵌入式C语言设计模式实现与优化实践 设计模式是软件工程中解决常见问题的经典方案,传统上多与面向对象语言关联。在嵌入式C语言开发中,通过结构体与函数指针的巧妙组合,同样可以实现23种经典设计模式。这种实现方式既保留了C语言的高效特性,又提升了代码的可维护性和扩展性。函数指针作为关键实现技术,通过运行时绑定实现了类似面向对象的多态特性。在STM32、ESP32等嵌入式平台中,这种模式特别适合资源受限环境,既能避免C++的运行时开销,又能获得良好的架构设计灵活性。文章通过工厂模式、观察者模式等典型案例,展示了在嵌入式菜单系统、硬件驱动抽象等场景中的 阅读详情

1. 项目概述:用C语言函数指针实现设计模式的必要性

在嵌入式开发领域,资源受限的环境决定了我们无法像Java等高级语言那样直接使用面向对象特性。但设计模式作为解决特定问题的经验总结,其思想价值与语言无关。通过结构体(struct)与函数指针的组合,我们可以在C语言中模拟出面向对象的关键特性——这正是嵌入式开发者必须掌握的硬核技能。

我曾在多个嵌入式项目中实践过这种模式化编程方法。比如在智能家居网关开发中,用状态机模式处理设备通信协议;在工业控制器里用观察者模式实现传感器数据分发。这种实现方式不仅保持了代码的清晰度,还让内存占用减少了约40%(相比面向对象的实现方式)。

2. 核心机制解析:结构体与函数指针的协同

2.1 结构体作为"类"的载体

在C++中,类天然包含数据成员和方法。而C语言中,我们可以用结构体模拟这种封装:

typedef struct {
    int data;
    void (*operation)(void* self);  // 函数指针成员
} MyClass;

这个结构体包含一个整型数据成员和一个操作函数指针,相当于简易的"类"声明。

2.2 函数指针的动态绑定

函数指针的精妙之处在于运行时的动态指定:

void ConcreteOperation(void* self) {
    MyClass* obj = (MyClass*)self;
    printf("Processing data: %d\n", obj->data);
}

MyClass instance = {
    .data = 42,
    .operation = ConcreteOperation  // 运行时绑定具体实现
};

通过将不同函数赋值给同一个函数指针,我们实现了类似多态的效果。这种技术在驱动开发中尤为常见,比如为不同型号的传感器注册各自的读写

当C语言遇见设计模式:用函数指针重构23种经典模式 本文探讨了如何在C语言中使用函数指针和结构体重构23种经典设计模式,实现类似面向对象的多态性和封装。通过详细代码示例展示了工厂模式、单例模式、适配器模式等核心模式的C语言实现方案,特别适合嵌入式系统和高性能中间件开发。 阅读详情

相关推荐

GoF设计模式C语言精解:从面向对象思想到系统级编程实践

设计模式是解决特定软件设计问题的经典、可复用的最佳实践方案,其核心价值在于提升代码的可维护性、可扩展性和复用性。通过封装变化点、解耦对象间依赖,设计模式为复杂系统的架构设计提供了经过验证的蓝图。在工程实践中,理解模式的本质比记忆具体实现更为重要。本文以C语言为载体,深入剖析GoF经典设计模式,通过结构体和函数指针等基础机制,映射面向对象的设计思想,如多态、组合和接口编程。这种实现方式尤其适用于系统级开发、嵌入式软件和底层框架构建,能帮助开发者夯实编程基础,理解大型系统中隐含的架构智慧。项目实战部分涵盖了工厂

weixin_29722783的博客 214

嵌入式C语言实现设计模式:struct与函数指针实践

设计模式是软件工程中解决常见问题的经典方案,传统上多与面向对象语言关联。在嵌入式开发领域,通过C语言的结构体(struct)与函数指针组合,可以巧妙实现策略模式、观察者模式等经典设计模式。这种技术方案既保留了C语言的高效性和低资源占用特点,又显著提升了代码的可维护性和扩展性。在嵌入式Linux驱动开发、RTOS应用等场景中,通过结构体封装数据与操作、利用函数指针实现多态,能够有效管理硬件抽象层、事件通知等复杂逻辑。实测表明,相比条件判断等传统方法,这种实现方式在STM32等MCU上可提升20%以上的执行效率

494

嵌入式C语言实现设计模式:结构体与函数指针的妙用

设计模式是提高代码可维护性和扩展性的重要方法,传统上多用于面向对象语言。在嵌入式开发中,C语言通过结构体与函数指针的组合,同样可以实现策略模式、观察者模式等经典设计模式。这种技术方案既保持了C语言的执行效率,又为嵌入式系统带来了更好的架构灵活性。在物联网设备开发、工业控制等领域,这种实现方式特别适用于通信协议切换、传感器数据处理等场景。通过合理使用函数指针和内存优化技巧,即使在资源受限的STM32等MCU上,也能构建出高效可靠的状态机和事件处理系统。

weixin_30509393的博客 366

Altium Designer20-柔性PCB绘制技巧

Altium Designer2020-柔性PCB绘制技巧 注:教程所用PCB随意找的,并没有完全绘制完,大家学习PCB折弯方法即可。 1.打开PCB,点击视图->板子规划模式1,如下图所示 2.点击设计->定义分割线,用两条分割线绘出要折弯的区域 3.点击设计->定义弯曲线(弯曲线呈现黄色) 4.用快捷键d,k进入layer manage stack(层叠管理器),在f...

weixin_44450279的博客 1万+

深度解析大语言模型中的词向量

​ 在学习完语言模型中的编码器与解码器知识后,让我们继续深入学习大语言模型中一个非常关键的技术:词向量表示,以及如何通过Transformer模型实现对next token的预测。 ​

产品老A,8年互联网大厂AIPM,专注探索新型人机交互 3281

面向可扩展的 ABAP CDS:EXTEND VIEW 全面实战与工程化指引

摘要: 本文深入讲解ABAP CDS的EXTEND VIEW功能,帮助开发者在标准或自建模型上安全扩展字段与关联。核心内容包括: 作用:避免直接修改标准CDS,通过轻量扩展添加业务字段和关联,降低维护风险。 语法要点:需定义CDS扩展实体名和Dictionary Append View名,支持添加普通字段、关联,但不允许聚合或修改原有结构。 限制:不能扩展含聚合、UNION的视图,且扩展字段需避免命名冲突。 工程实践:建议使用客户命名空间,区分结构扩展与元数据扩展,并注意功能性变更需通过其他方式实现。 示例

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 392

Linux 下安装 openjdk 17【详细步骤】

JDK17,安装教程。

甘蓝的专栏 7500

UNet 改进(19):与ASPP结合的图像分割模型

这个代码实现了一个改进版的UNet模型,在传统的UNet架构基础上,引入了ASPP模块来增强模型捕获多尺度上下文信息的能力。​​UNet主干网络​​:经典的编码器-解码器结构,带有跳跃连接​​ASPP模块​​:位于瓶颈层,用于提取多尺度特征。

2401_82355416的博客 877

掌握 Unity 中的状态机:综合指南

最后,将拥有一个由状态机驱动的功能齐全的播放器控制器,可以集成到自己的项目中。此外,状态机有助于实现复杂的人工智能、玩家控制、动画系统等,从而形成更强大、更灵活的游戏架构。状态机是计算机科学和游戏开发中的一个基本概念,它通过定义一组有限的状态及其之间的转换来模拟实体的行为。你可以定义常见的状态行为,例如 Enter、Update 和 Exit 方法,确保整个状态机架构的一致性和连贯性。由于前面提到的状态类扩展了 BaseState 类,因此我们可以为具有不同状态的不同对象创建单独的类。

yolo模型训练找我,AI游戏合作找我 1449

一文搞懂LDO !

Start-up 时间是 IC 做死的,如果想要延时启动,最简单的办法是在 EN 上接一个大一些的电容到地,构成一个简单的 RC 电路。电容太小,电压跌落大,响应快。输出电流高,功率大;外围器件少,电路简单,成本低,负载响应快,输出纹波小;将采集的电压输入到比较器反向输入端,与正向输入端的基准电压(期望输出的电压)进行比较,再将比较结果进行放大;是指在给定负载变化下的输出电压的变化,这里的负载变化通常是从无负载到满负载。芯片的静态电流大小与其他性能成反关系,如低噪声,高电源电压抑制比,静态电流大。

weixin_46969363的博客 4382

第95节:多模型多卡推理管理

多模型推理:在同一硬件平台上同时部署多个不同或相同的深度学习模型,满足多任务需求。多卡推理:利用多块 GPU 资源,提升推理吞吐量与并发能力。目标:合理分配 GPU 资源,实现高效、低延迟的推理服务。

yumeiguo的博客 217

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 深入解析GPIO中断与寄存器操作:从原理到嵌入式系统实战
下一篇: ARM Cortex-A MPU子系统时钟、复位与电源管理深度解析与实战
de1981
博客等级 码龄12年 8粉丝 208原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值