从C函数返回状态代码和指针的经典方法

问题描述 投票:0回答:2

我目前正在阅读this question,其中显示了有关使用void **作为参数从函数返回指针的问题。

我的代码大多以状态码作为返回值,现在我正在寻找其他方法来返回这些指针和状态码。因此,我目前看到了两个选择,但没有一个能让我感到高兴。可能我想得有些迟。

// Output status through return value and the pointer through parameter 
// - seems to be problematic because it requires casting to void **, which is invalid
int myfunc(void **output);

// Output status through return value, pointer through struct 
// - seems to add unnecessary complexity to the interface
struct some_output { void *value };
int myfunc(struct some_output *output);

// Output pointer through return value, status through parameter 
// - breaks consistency with other interfaces which always return the status code
void *myfunc(int *status);

现在,我想知道是否还有其他替代的优雅方法可以从我没有想到的没有“缺点”的函数中返回指针和状态代码?

c pointers void
2个回答
0
投票

使用'C',当函数仅限于返回单个值时,没有一种完美的方法。几乎没有常用的模式,后面是各种可用的API。考虑使用一种经过验证的,次于完美的方法:

  • int状态=函数(*输出,输入);

  • int结果= function(*输出,输入);带有扩展的错误代码。

    • 与用于许多系统调用一起使用,'errno'中有额外的错误详细信息。
    • 在某些系统上,附加的错误详细信息随功能提供,使MT应用程序更易于使用。
  • bool成功= function(*输出,输入);有回调错误

    • 轻松通过成功/失败。
    • 错误信息传递给用户定义的错误回调。
    • 已在许多GUI回调(例如X11)中实现,已经使用了回调。
  • 结构结果* res = function(input,struct errro ** error)

    • 在Glib或其他处理复杂数据类型(不仅仅是数组)的库中使用
    • 通常,每个结构将具有相应的free *功能。
    • 错误地址(如果通过)将捕获错误数据。
    • 错误将导致res = NULL,并且设置了错误。
    • 更紧密地尝试/抓住。

当引入通用调用时,通常通常将输出和错误对象放在同一位置。在许多情况下,输出被放置为第一个参数,错误/异常被放置在末尾。

值得关注Error handling in C code


-1
投票

我同意@Mat的用法:

typedef Gret struct generic_ret;
struct generic_ret {
    int Status;
    union {
     void *p;
     DialPlan *d;
    };
}
...
Phone = GetPhone(...);
if (Phone.Status == 0) {
     Dial(Phone.d);
     ...
}

继续进行下去,您将最终在Go中进行编程...状态和指针的另一种[[classic方法是保留比0多的指针值:

extern DialPlan *DP_NoService, *DP_BadNumber, *DP_Broke, ...; extern bool IsDialError(DialPlan *p); .... static DialPlan *DP_FirstError = 0, *DP_NoService = (void *)1, *DP_BadNumber = (void *)2, *DP_LastError = (void *)10; bool IsDialError(DialPlan *p) { return (p > DP_FirstError && p < DP_LastError); }
或者,如果您更喜欢安全外观:

static DialPlan Errors[10]; static DialPlan *DP_NoService = Errors + 0, *DP_BadNumber = Errors + 1, ... *DP_LastError = Errors + 9;

© www.soinside.com 2019 - 2024. All rights reserved.