简体   繁体   English

如何从 void* 转换为 c 结构

[英]How to do a cast from void* to a c struct

I have this struct我有这个结构

typedef struct tournament_t
{
 Map players;
}*Tournament;

the Map Adt used in the struct is generic and uses this typedef for void*结构中使用的 Map Adt 是通用的,并将此 typedef 用于void*

/** Data element data type for map container */
typedef void *MapDataElement;

I want a Copy Function for the Tournament struct and it has to be with type MapDataElement so this is the function我想要一个用于锦标赛结构的副本 Function,它必须是MapDataElement类型,所以这是 function

MapDataElement tournamentCopy(MapDataElement tournament)
{
 //some code
 Tournament ptr = *(Tournament*)tournament;
    copy->players=mapCopy(ptr->players);
//some code
}

the problem is that no matter what i do ptr->players is always null when I tried to change the type that the function gets from MapDataElement to Tournament everything worked fine, However I am not allowed to change it so... any ideas?问题是,无论我做什么ptr->players总是 null 当我尝试将 function 从MapDataElement获取的类型更改为Tournament时,一切正常,但是我不允许更改它所以......有什么想法吗?

You have pointer confusion.你有指针混淆。 Use:利用:

typedef struct tournament_t
{
    Map players;
}Tournament;


typedef struct mapdataelement_t
{
     // definition
} MapDataElement;

and now:现在:

MapDataElement *tournamentCopy(MapDataElement *tournament)
{
    Tournament *ptr = (Tournament *)tournament;

The root of all your problems is trying to hide pointers behind typedefs which makes the code needlessly complex and unreadable - you are only creating a bunch of problems for yourself with this.所有问题的根源是试图将指针隐藏在 typedef 后面,这使代码变得不必要的复杂和不可读 - 你只会为自己制造一堆问题。

Simply do:只需这样做:

typedef struct 
{
  Map players;
} tournament_t;

I want a Copy Function for the Tournament struct and it has to be with type MapDataElement我想要一个用于 Tournament 结构的副本 Function,它必须是 MapDataElement 类型

Ok so make MapDataElement something that makes sense, void* probably does not.好的,所以让MapDataElement有意义, void*可能没有。 If you want it to be some sort of generic item container then typedef it as such:如果您希望它是某种通用项目容器,那么 typedef 它是这样的:

typedef struct
{
  void* data;
  size_t size;
  // whatever makes sense to include here, an enum to list types perhaps?
} MapDataElement;

And finally, modern C allows you to do type safe, type-generic programming without dangerous void pointers:最后,现代 C 允许您在没有危险 void 指针的情况下进行类型安全、类型通用的编程:

#define something_copy(x) _Generic((x), \
  tournament_t: tournament_copy,        \
  thingie_t:    thingie_copy) (x)

This means that the function-like macro "something_copy" will call the relevant specific function based on the type passed.这意味着类函数宏“something_copy”将根据传递的类型调用相关的具体function。 Or if you pass a wrong type not supported - a compiler error.或者,如果您传递了不支持的错误类型 - 编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM