参数使用 void 指针传递多个值

Parameter passing multiple values using void pointer

我想使用 void 指针将多个参数传递给一个函数。

void* function(void *params)
{
//casting pointers
//doing something
}
int main()
{
  int a = 0
  int b = 10;
  char x = 'S';
  void function(???);
  return 0;
}

我知道我必须将它们转换为函数中的某个变量,但我不知道如何将我的 3 个参数作为一个空指针传递给我的函数。

我已经搜索了这个问题很长时间了,但我找不到任何可以帮助我的东西。

void* 用作指向 "generic" 类型的指针。因此,您需要创建一个包装类型,cast 转换为 void* 以调用该函数,然后 cast 转换回您在函数中的类型正文

#include <stdio.h>

struct args { int a, b; char X; };
void function(void *params)
{
  struct args *arg = params;
  printf("%d\n", arg->b);
}
int main()
{
  struct args prm;
  prm.a = 0;
  prm.b = 10;
  prm.X = 'S';
  function(&prm);
  return 0;
}

你可以这样做:

struct my_struct
{
   int a;
   int b;
   char x;
}

void * function(void * pv)
{
  struct my_strcut * ps = pv; /* Implicitly converting the void-pointer 
                              /* passed in to a pointer to a struct. */

  /* Use ps->a, ps->b and ps->x here. */

  return ...; /* NULL or any pointer value valid outside this function */
}

这样使用

int main(void)
{
  struct my_struct s = {42, -1, 'A'};

  void * pv = function(&s);
}

跟进

struct my_struct_foo
{
   void * pv1;
   void * pv2;
}

struct my_struct_bar
{
   int a;
   int b;
}

void * function(void * pv)
{
  struct my_strcut_foo * ps_foo = pv; 
  struct my_struct_bar * ps_bar = ps_foo->pv1;

  /* Use ps_foo->..., ps_bar->... here. */

  return ...; /* NULL or any pointer value valid outside this function */
}

这样使用

int main(void)
{
  struct my_struct_bar s_bar = {42, -1};
  struct my_struct_foo s_foo = {&s_bar, NULL};

  void * pv = function(&s_foo);
}