簡體   English   中英

如何在C中向結構轉換void指針?

[英]How do I cast a void pointer to a struct in C?

在我編寫代碼的項目中,我有一個void指針,“implementation”,它是“Hash_map”結構的成員,並指向“Array_hash_map”結構。 這個項目背后的概念不太現實,但請耐心等待。 在我可以在任何函數中使用它之前,項目的規范要求我將void指針“implementation”轉換為“Array_hash_map”。

我的問題,特別是,我在將函數轉換為所需結構的函數中做了什么? 每個函數頂部是否有一個語句可以強制轉換它們,還是每次使用“實現”時都會進行轉換?

下面是使用Hash_map和Array_hash_map的結構的typedef以及使用它們的幾個函數。

typedef struct {
  Key_compare_fn key_compare_fn;
  Key_delete_fn key_delete_fn;
  Data_compare_fn data_compare_fn;
  Data_delete_fn data_delete_fn;
  void *implementation;
} Hash_map;

typedef struct Array_hash_map{
  struct Unit *array;
  int size;
  int capacity;
} Array_hash_map;

typedef struct Unit{
  Key key;
  Data data;
} Unit;

職能:

/* Sets the value parameter to the value associated with the
   key parameter in the Hash_map. */
int get(Hash_map *map, Key key, Data *value){
  int i;
  if (map == NULL || value == NULL)
    return 0;
  for (i = 0; i < map->implementation->size; i++){
    if (map->key_compare_fn(map->implementation->array[i].key, key) == 0){
      *value = map->implementation->array[i].data;
      return 1;
    }
  }
  return 0;
}

/* Returns the number of values that can be stored in the Hash_map, since it is
   represented by an array. */
int current_capacity(Hash_map map){
  return map.implementation->capacity;
}

您可以在每次使用時進行轉換,也可以將其轉換一次並將值保存到臨時變量中。 后者通常是最干凈的方法。

例如,您可以使用以下內容:

void my_function (Hash_Map* hmap) {
    Array_hash_map* pMap;

    pMap = hmap->implementation;

    // Now, you are free to use the pointer like it was an Array_hash_map
    pMap->size = 3; // etc, etc
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM