1

私がコードを書いているプロジェクトでは、「Hash_map」構造体のメンバーであり、「Array_hash_map」構造体を指す void ポインター「implementation」があります。このプロジェクトの背後にあるコンセプトはあまり現実的ではありませんが、ご了承ください。プロジェクトの仕様では、関数で使用する前に、void ポインターの「実装」を「Array_hash_map」にキャストするよう求めています。

私の質問は、具体的には、関数で void ポインターを目的の構造体にキャストするにはどうすればよいですか? それらをキャストする各関数の上部に1つのステートメントがありますか、それとも「実装」を使用するたびにキャストを行いますか?

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;
}
4

1 に答える 1

4

使用するたびにキャストすることも、一度キャストして値を一時変数に保存することもできます。通常、後者が最もクリーンな方法です。

たとえば、次のようなものを使用できます。

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
}
于 2010-05-04T00:04:35.730 に答える