Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a C function return an arbitrary type?

Tags:

c

types

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.

like image 736
Sarkreth Avatar asked Jun 16 '14 17:06

Sarkreth


1 Answers

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);
like image 55
johnnycrash Avatar answered Sep 24 '22 11:09

johnnycrash