static變量和函數如何巧妙調用


app.c 和 main.c 之間,在main.c中調用app.c的static變量和函數,需要利用一個結構體結合指針通過傳地址的方式間接訪問。

app   --------------------------------main

        struct { int , func()}作為一種通道或載體

        

直接上一個代碼:

/*main.c*/
#include "common.h"
int main(void)
{
    int i;
    unsigned char cp[8];

    FUNC_PTR ptrs;
    use_func(&ptrs); /*get addr of func(pointer)*/
    ptrs.pfunc();/*use the member of struct*/
    
    /*get buff and *length*/
    memcpy(cp,ptrs.ptr,*ptrs.length);
    for(i = 0; i < (int)*ptrs.length; i++)
        printf("%d-0x%02x ",i,cp[i]);
    printf("\n");
    return 0;
}
/*app.c*/
#include "common.h"
static unsigned char buff[8];
static int len;
static void func(void);

static void func(void)
{
    unsigned char temp[8] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08};
    int i;
    len = 8;
    memcpy(buff,temp,len);
    for(i = 0; i < len; i++)
        printf("%d-0x%02x ",i,buff[i]);
    printf("\n");
}

void use_func(FUNC_PTR *function)
{
    function->pfunc = func;
    function->ptr = buff;
    function->length = &len;
}
/*common.h*/
#ifndef _COMMON_H_
#define _COMMON_H_

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct structs{
    void (*pfunc)(void);
    unsigned char *ptr;
    int *length;
}FUNC_PTR;

extern void use_func(FUNC_PTR *pfunc);
#endif

以上三個文件歸納為main.c app.c common.h 

 

結構體里面均為指針,利用一個use_func(FUNC_PTR *pfunc) 進行在app.c 的所有初始化賦值,包括函數指針的指向。

實際上利用如下:

ptrs.pfunc
ptrs.ptr
ptrs.length 地址
**********
ptrs.pfunc();
memcpy(cp,ptrs.ptr,*ptrs.length);

運行效果如下:

0-0x01 1-0x02 2-0x03 3-0x04 4-0x05 5-0x06 6-0x07 7-0x08 
0-0x01 1-0x02 2-0x03 3-0x04 4-0x05 5-0x06 6-0x07 7-0x08

通過static定義,可以通過結構體作為通道基於指針引用。

推廣而言,在非static即可直接利用extern引用外部變量或者函數。

但是也可以利用如static的實現方式去處理。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM