简体   繁体   中英

Can I make a C function return an arbitrary type?

I've written a function that interprets serial data (CAN) and currently returns a float. I'd like the function to include an argument wherein the user specifies a return type in a string, and the function returns a value of that type. It's just a convenience thing, to avoid having to write multiple functions that share almost all of the same code.

Pass a void pointer to the type of data you want returned.

void foo(char* szType, void *pOut) {
  switch (szType[0]) {
    case 'I': *(int*)pOut = 1; break;
    case 'F': *(float*)pOut = 1; break;
  }
}

use like this:

int a;
float b;
foo("I", &a);
foo("F", &b);

johnnycrash's answer is correct, but there is another way if you want to return an object of a specific type (rather than use the call-with-parameter-equal to void * pointer). That works by returning a malloc() 'd object of the type requested.

#include <stdio.h>
#include <stdlib.h>

void *
foo (char *mytype)
{
  switch (mytype[0])
    {
    case 'I':
      {
        int *i = malloc (sizeof (int));
        *i = 1;
        return i;
      }
    case 'F':
      {
        double *d = malloc (sizeof (double));
        *d = 1.234;
        return d;
      }
    default:
      return NULL;
    }
}

int
main (int argc, char **argv)
{
  int *ii;
  double *dd;

  ii = foo ("I");
  printf ("Integer is %d\n", *ii);
  free (ii);

  dd = foo ("F");
  printf ("Double is %f\n", *dd);
  free (dd);
  exit (0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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