我可以让 C 函数返回任意类型吗? [英] Can I make a C function return an arbitrary type?

查看:34
本文介绍了我可以让 C 函数返回任意类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数来解释串行数据 (CAN) 并且当前返回一个浮点数.我希望该函数包含一个参数,其中用户在字符串中指定返回类型,并且该函数返回该类型的值.这只是一件方便的事情,以避免必须编写多个共享几乎所有相同代码的函数.

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

像这样使用:

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

这篇关于我可以让 C 函数返回任意类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆