首页 > 解决方案 > 从 C 函数返回状态码和指针的优雅方法

问题描述

我目前正在阅读这个问题,它显示了有关使用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);

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

标签: cpointersvoid

解决方案


使用“C”,当函数仅限于返回单个值时,没有一种完美的方法。常用的模式很少,然后是各种可用的 API。考虑坚持使用一种经过验证但不太完美的方法:

  • int status = function(struct Result *output, input) ;

    • 处理简单的案例,成功/失败的次数很少。
    • 常用 0 表示成功,负数表示错误。
  • int 结果 = 函数(*输出,输入);带有扩展的错误代码。

    • 用于许多 Linux 系统调用/API,“errno”中的额外错误详细信息。
    • 常用 0 表示成功,负数表示错误。
    • 由于单一错误代码,MT 系统面临挑战。在许多情况下,错误信息实际上可用作包装线程本地结果的函数。
  • 布尔成功 = 函数(*输出,输入);有回调错误

    • 使传递成功/失败变得容易。
    • 错误信息传递给用户定义的错误回调。
    • 在许多 GUI 回调(例如 X11)中实现,已经使用回调。
  • 结构结果 *res = 函数(输入,结构 errro **错误)

    • 用于处理复杂数据类型(不仅仅是数组)的 Glib 或其他库
    • 通常,每个结构都会有相应的 free* 函数。
    • 错误地址(如果通过)将捕获错误数据。
    • 错误将导致 res = NULL,并设置错误。
    • 在精神上更接近尝试/捕捉。

在引入泛型调用时,我观察到的共同主题通常是将输出和错误对象放在参数列表中的同一位置(不必一起!)。在许多情况下,输出放在第一位,错误/异常放在最后。

值得研究C 代码中的错误处理


推荐阅读