今天我来说几个在嵌入式开发中常用的C语言技巧吧。也许你曾经用过,也许你只是见到过但是没有深入理解。那么今天好好补充下吧^_^
1.指向函数的指针
指针不光能指向变量、字符串、数组,还能够指向函数。在C语言中允许将函数的入口地址赋值给指针。这样就可以通过指针来访问函数。还可以把函数指针当成参数来传递。函数指针可以简化代码,减少修改代码时的工作量。通过接下来的讲解大家会体会到这一点的。
/*函数指针简单讲解
*通过指向函数的指
*针调用比较两个数
*大小的程序
*/
#include <iostream>
using namespace std;
/*比较函数声明*/
int max(int,int);
/*指向函数的指针声明(此刻指针未指向任何一个函数)*/
int (*test)(int,int);
int
main(int argc,char* argv[])
{
int largernumber;
/*将max函数的入口地址赋值给
*函数指针test
*/
test=max;
/*通过指针test调用函数max实
*现比较大小
*/
largernumber=(*test)(1,2);
cout<<largernumber<<endl;
return 0;
}
int
max(int a,int b)
{
return (a>b?a:b);
}
通过注释大家应该很容易理解,函数指针其实和变量指针、字符串指针差不多的。如果大家理解了这个小程序,那么理解起下面这个有关Nand flash的源代码就好多了。
typedef struct {
void (*nand_reset)(void);
void (*wait_idle)(void);
void (*nand_select_chip)(void);
void (*nand_deselect_chip)(void);
void (*write_cmd)(int cmd);
void (*write_addr)(unsigned int addr);
unsigned char (*read_data)(void);
}t_nand_chip;
static t_nand_chip nand_chip;
/* NAND Flash操作的总入口, 它们将调用S3C2410或S3C2440的相应函数 */
static void nand_reset(void);
static void wait_idle(void);
static void nand_select_chip(void);
static void nand_deselect_chip(void);
static void write_cmd(int cmd);
static void write_addr(unsigned int addr);
static unsigned char read_data(void);
/* S3C2410的NAND Flash处理函数 */
static void s3c2410_nand_reset(void);
static void s3c2410_wait_idle(void);
static void s3c2410_nand_select_chip(void);
static void s3c2410_nand_deselect_chip(void);
static void s3c2410_write_cmd(int cmd);
static void s3c2410_write_addr(unsigned int addr);
static unsigned char s3c2410_read_data();
/* S3C2440的NAND Flash处理函数 */
static void s3c2440_nand_reset(void);
static void s3c2440_wait_idle(void);
static void s3c2440_nand_select_chip(void);
static void s3c2440_nand_deselect_chip(void);
static void s3c2440_write_cmd(int cmd);
static void s3c2440_write_addr(unsigned int addr);
static unsigned char s3c2440_read_data(void);
/* 初始化NAND Flash */
void nand_init(void)
{
#define TACLS 0
#define TWRPH0 3
#define TWRPH1 0
/* 判断是S3C2410还是S3C2440 */
if ((GSTATUS1 == 0x32410000) || (GSTATUS1 == 0x32410002))
{
nand_chip.nand_reset = s3c2410_nand_reset;
nand_chip.wait_idle = s3c2410_wait_idle;
nand_chip.nand_select_chip = s3c2410_nand_select_chip;
nand_chip.nand_deselect_chip = s3c2410_nand_deselect_chip;
nand_chip.write_cmd = s3c2410_write_cmd;
nand_chip.write_addr = s3c2410_write_addr;
nand_chip.read_data = s3c2410_read_data;
/* 使能NAND Flash控制器, 初始化ECC, 禁止片选, 设置时序 */
s3c2410nand->NFCONF = (1<<15)|(1<<12)|(1<<11)|(TACLS<<8)|(TWRPH0<<4)|(TWRPH1<<0);
}
else
{
nand_chip.nand_reset = s3c2440_nand_reset;
nand_chip.wait_idle = s3c2440_wait_idle;
nand_chip.nand_select_chip = s3c2440_nand_select_chip;
nand_chip.nand_deselect_chip = s3c2440_nand_deselect_chip;
nand_chip.write_cmd = s3c2440_write_cmd;
#ifdef LARGER_NAND_PAGE
nand_chip.write_addr = s3c2440_write_addr_lp;
#else
nand_chip.write_addr = s3c2440_write_addr;
#endif
nand_chip.read_data = s3c2440_read_data;