简体   繁体   English

我可以让C函数返回任意类型吗?

[英]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. 我编写了一个解释串行数据(CAN)的函数,当前返回一个浮点数。 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指针传递给要返回的数据类型。

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). johnnycrash的答案是正确的,但如果你想返回一个特定类型的对象(而不是使用call-with-parameter-equal- void *指针),还有另一种方法。 That works by returning a malloc() 'd object of the type requested. 这是通过返回所请求类型的malloc() 'd对象来实现的。

#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);
}

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

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