2017-04-05 79 views
1

我有一个巨大的结构数组,我创建了不同的功能,根据成员的值来获得结构指针:我们会根据成员的struct值

typedef struct { 
    uint32_t a; 
    uint32_t b; 
    uint32_t c; 
    uint32_t d; 
} test_t; 

test_t test[10]; // Initialized somewhere else 

static test_t* __get_struct_by_a(uint_32_t a) { 
    for (uint32_t i = 0; i < 10; i++) { 
     if (test[i].a == a) 
      return &test[i]; 
    } 
    return NULL; 
} 

static test_t* __get_struct_by_b(uint_32_t b) { 
    ... 
} 

有没有一种简单的方法用C来解决这个代替为每个成员创建一个查找函数?

回答

0

以下是一种编写通用函数以获取(查找)您的第一个匹配结构成员的方法。

我试图保持与你的示例代码一致,增加了一些#include指令可能是必要的,一个典型的固定阵列尺寸为#define这样TEST_SIZE你不为循环指数使用硬编码值。

#include <stddef.h> 
#include <stdio.h> 
#include <string.h> 

typedef struct { 
    uint32_t a; 
    uint32_t b; 
    uint32_t c; 
    uint32_t d; 
} test_t; 

test_t test[10]; // Initialized somewhere else 
#define TEST_SIZE (sizeof(test)/sizeof(test[0])) 

static test_t* __get_struct_by_offset(const void* value_ptr, const size_t offset, const size_t field_size) 
{ 
    for (uint32_t i = 0; i < TEST_SIZE; i++) 
    { 
     if (0 == memcmp(value_ptr, ((unsigned char*)&test[i])+offset, field_size)) 
     { 
      return &test[i]; 
     } 
    } 
    return NULL; 
} 

你会使用这样的:

uint32_t a_value_to_find = 5; /* example field "a" value to find */ 
    uint32_t b_value_to_find = 10; /* example field "b" value to find */ 
    test_t* test_ptr; 

    /* find specified value for field "a" */ 
    test_ptr = __get_struct_by_offset(&a_value_to_find, offsetof(test_t, a), sizeof(a_value_to_find)); 

    /* find specified value for field "b" */ 
    test_ptr = __get_struct_by_offset(&b_value_to_find, offsetof(test_t, b), sizeof(b_value_to_find)); 

这是你的责任,以确保在指定的offset*value_ptr的数据类型和领域是相同的,因此同样大小的(field_size )。

为了简化使用,您可以编写一些宏作为这些调用的简写。例如:

#define GET_A(value) __get_struct_by_offset(&value, offsetof(test_t, a), sizeof(value)) 
#define GET_B(value) __get_struct_by_offset(&value, offsetof(test_t, b), sizeof(value)) 

对于查询 “A” 和 “B”,然后简化为:

/* find specified value for field "a" */ 
    test_ptr = GET_A(a_value_to_find); 

    /* find specified value for field "b" */ 
    test_ptr = GET_B(b_value_to_find); 
+0

感谢菲尔这是一个非常巧妙的解决办法! –