简体   繁体   English

如何在C中向结构转换void指针?

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

In a project I'm writing code for, I have a void pointer, "implementation", which is a member of a "Hash_map" struct, and points to an "Array_hash_map" struct. 在我编写代码的项目中,我有一个void指针,“implementation”,它是“Hash_map”结构的成员,并指向“Array_hash_map”结构。 The concepts behind this project are not very realistic, but bear with me. 这个项目背后的概念不太现实,但请耐心等待。 The specifications of the project ask that I cast the void pointer "implementation" to an "Array_hash_map" before I can use it in any functions. 在我可以在任何函数中使用它之前,项目的规范要求我将void指针“implementation”转换为“Array_hash_map”。

My question, specifically is, what do I do in the functions to cast the void pointers to the desired struct? 我的问题,特别是,我在将函数转换为所需结构的函数中做了什么? Is there one statement at the top of each function that casts them or do I make the cast every time I use "implementation"? 每个函数顶部是否有一个语句可以强制转换它们,还是每次使用“实现”时都会进行转换?

Here are the typedefs the structs of a Hash_map and Array_hash_map as well as a couple functions making use of them. 下面是使用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;

functions: 职能:

/* 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;
}

You can cast it each time you use it, or you can cast it once and save the value to a temporary variable. 您可以在每次使用时进行转换,也可以将其转换一次并将值保存到临时变量中。 The latter is usually the cleanest method. 后者通常是最干净的方法。

For example, you could use something like: 例如,您可以使用以下内容:

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