以下是一种编写通用函数以获取(查找)您的第一个匹配结构成员的方法。
我试图保持与你的示例代码一致,增加了一些#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);
感谢菲尔这是一个非常巧妙的解决办法! –