通过数组去索引结构体指针效果还不错,这样可以避免很多同样或者类似的代码重复的编写,基于VC6.0的平台。
#include "stdio.h" #include "string.h" #define MAX_LEN 32 #define PCSTR const char * #define PSTR char * typedef enum { STRUCT0_ID = 0, STRUCT1_ID, STRUCT_MAX_ID, }EStructPara; typedef struct { char Str0[MAX_LEN+1]; char Str1[MAX_LEN+1]; }TString; typedef struct { unsigned int IntVar0; unsigned int IntVar1; unsigned int IntVar2; }TIntVar; TString tTestStr = {"aaa", "123"}; TIntVar tTestVar = {123456, 987654, 100000}; PCSTR GlobalTable[STRUCT_MAX_ID] = { (PCSTR)(&tTestStr), // (PCSTR)((TString *)&tTestStr), (PCSTR)(&tTestVar), // (PCSTR)((TIntVar *)&tTestVar), }; PSTR GetInfoPoint(EStructPara type) { if ((type >= STRUCT0_ID) && (type < STRUCT_MAX_ID)) { return (PSTR)GlobalTable[type]; } return NULL; } void GetInfoStruct(void *InputPara, EStructPara type, int length) { if ((type >= STRUCT0_ID) && (type < STRUCT_MAX_ID)) { memcpy(InputPara, GlobalTable[type], length); } return; } void TestInfoPoint(void) { TString *tTmpStr = NULL; TIntVar *tTmpInt = NULL; printf("/nTestInfoPoint function run !/n"); tTmpStr = (TString *)GetInfoPoint(STRUCT0_ID); printf("/ntTmpStr->Str0:%s/ntTmpStr->Str1:%s/n", tTmpStr->Str0, tTmpStr->Str1); tTmpInt = (TIntVar *)GetInfoPoint(STRUCT1_ID); printf("/ntTmpInt->IntVar0:%d/ntTmpInt->IntVar1:%d/ntTmpInt->IntVar2:%d/n", tTmpInt->IntVar0, tTmpInt->IntVar1, tTmpInt->IntVar2); } void TestInfoStruct(void) { TString tTmpStr = {0}; TIntVar tTmpInt = {0}; printf("/n--------------------------------/n"); printf("TestInfoStruct function run !/n"); GetInfoStruct(&tTmpStr, STRUCT0_ID, sizeof(TString)); printf("/ntTmpStr.Str0:%s/ntTmpStr.Str1:%s/n", tTmpStr.Str0, tTmpStr.Str1); GetInfoStruct(&tTmpInt, STRUCT1_ID, sizeof(TIntVar)); printf("/ntTmpInt.IntVar0:%d/ntTmpInt.IntVar1:%d/ntTmpInt.IntVar2:%d/n", tTmpInt.IntVar0, tTmpInt.IntVar1, tTmpInt.IntVar2); } int main(int argc, char **argv) { TestInfoPoint(); TestInfoStruct(); return 0; }